Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
I have a gridview of which there is information displayed from two database tables. I want to select the business name from the "Business name" column and the value from the cell based on the row that the user selects 'viewfile' and assign it to a string variable.

Here is my code(note the gridview is not displayed on the page_load but after a 'search content' button is clicked)

C#
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
           
            try
            {
                switch (e.CommandName)
                {

                    case "view":
                        
                        String name = GridView1.Rows[4].Cells[4].FindControl("Business_Name").ToString(); 
                        string filename = e.CommandArgument.ToString();
                        string path = Server.MapPath("~/BusinessProfilesContent/" + name + "/" + filename);
                        byte[] bts = System.IO.File.ReadAllBytes(path);
                        Response.Clear();
                        Response.ClearHeaders();
                        Response.ContentType = "image";
                        Response.WriteFile(path);
                        Response.Flush();
                        Response.End();
                        break;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);

            }
        }


Here is the webform code:

ASP.NET
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
                        EmptyDataText = "No files uploaded" Width="766px" onrowcommand="GridView1_RowCommand">
    <Columns>
       <asp:BoundField DataField = "Incident_ID" HeaderText = "Incident ID" />
       <asp:BoundField DataField = "Incident_Type_Name" HeaderText = "Incident Type" />
       <asp:BoundField DataField = "Description" HeaderText = "Description" />
       <asp:BoundField DataField = "Date_Time" HeaderText = "Date and time of Upload" />
       <asp:BoundField DataField = "Business_Name" HeaderText = "Business Name" />
       <asp:BoundField DataField = "Provence" HeaderText = "Provence" />
       <asp:BoundField DataField = "County" HeaderText = "County" />
       <asp:BoundField DataField = "Username" HeaderText = "Username" />
       <asp:ImageField DataImageUrlField="File_Path" ControlStyle-Width="100"
        ControlStyle-Height = "100" HeaderText = "Preview Image"/>
        <asp:TemplateField ItemStyle-HorizontalAlign = "Center">
            <ItemTemplate>
               <asp:LinkButton ID="LinkButton1"  runat="server" CausesValidation="false" CommandName="view" CommandArgument = '<%#Eval("FileName")%>' >ViewFile</asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
Posted
Comments
ZurdoDev 26-Feb-14 10:43am    
Where are you stuck?
Member 10609511 26-Feb-14 11:57am    
I am getting error - object reference not set to an instance of an object. Basically depending on which row the users selects the link button 'view file' from I want to take the value of the cell in that row under column 'Business Name'

According to your comment (not in your original post) you are getting an exception.
Quote:
object reference not set to an instance of an object

I think it is this line that is firing that exception
String name = GridView1.Rows[4].Cells[4].FindControl("Business_Name").ToString();

Firstly, I don't think you need the .FindControl("Business Name") - you don't have a control called that - it's the title of one of your columns... column index 4 in fact.
Secondly, you are always looking at row index 4 on your datagrid ... what if you haven't got 5 rows in there?
Both of these issues could have produced that error.

Now to solve it ...
That parameter GridViewCommandEventArgs e comes in handy for finding the row that was selected...
int i = Convert.ToInt32(e.CommandArgument);
GridViewRow r = GridView1.Rows[i];

Next you want the cell that corresponds to the "Business Name" column - I already know that this is column index 4 so your code becomes
String name = r.Cells[4].Text;

If you don't want to Hard-Code the column number (and you shouldn't want to) have a look at this post on StackOverflow[^] to get the column based on its name
 
Share this answer
 
v2
Comments
Member 10609511 26-Feb-14 13:19pm    
When I try that I get this error:

Input string was not in a correct format.

It is coming from the line

int i = Convert.ToInt32(e.CommandArgument);

When I run the debugger...
CHill60 26-Feb-14 13:46pm    
Strange. When you run the debugger what are the contents of e.CommandArgument?
Member 10609511 26-Feb-14 13:55pm    
The contents are the file name eg.123.jpg however I found a solution to the problem online but it seems to select only the first row(row index remains at 0)

int index;
bool bIsConverted = int.TryParse(e.CommandArgument.ToString(), out index);
CHill60 26-Feb-14 14:10pm    
In your Webform code try changing your line for CommandArgument to CommandAgument ="<%#((GridViewRow)Container).RowIndex%>" + ";" + %#Eval("FileName")%> />. This will pass in your filename AND the row index. Access the specific argument e.g. string RowId = e.Values["RowIndex"].ToString(); int i = Convert.ToInt32(RowId);
Apologies ... there may be typing errors in this but I can't check it out at the moment
Member 10609511 26-Feb-14 14:43pm    
There Seems to be error in your code somewhere, the line:

string RowId = e.CommandArgument.["RowIndex"].ToString();

Gives the error: Identifier expected

Here is what I have in the asp code for gridview:

<itemtemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" CommandName="view" CommandArgument = ''<%#((GridViewRow)Container).RowIndex%>' + ';' + '<%#Eval("FileName")%>''>ViewFile


I found this elsewhere but not sure how to implement
ImageButton b = (ImageButton)sender;
GridViewRow row = (GridViewRow)b.NamingContainer;
if (row != null)
{
//Get the Row Index
int rowIndex = row.RowIndex;
//Get the DataKey value
string key = GridView1.DataKeys[rowIndex].Value.ToString();
//Get the Row value of BoundField
string rowValue = row.Cell[0].Text;


}
C#
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
           
           
            try
            {
                switch (e.CommandName)
                {

                    case "view":
                        
                        LinkButton l = e.CommandSource as LinkButton; 
                        
                        GridViewRow selectedRow = l.NamingContainer as GridViewRow ;
                        
                        int intRowIndex = Convert.ToInt32(selectedRow.RowIndex);
               
                        GridViewRow row = GridView1.Rows[intRowIndex];
                        String name = Server.HtmlDecode(row.Cells[4].Text); 
                        string filename = e.CommandArgument.ToString();
                        String ext = String.Empty;
                        string path = Server.MapPath("~/BusinessProfilesContent/" + name + "/" + filename);
                        SqlConnection conn;
                        SqlCommand comm;
                        String connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
                        conn = new SqlConnection(connectionString);
                        comm = new SqlCommand("SELECT Incident.File_Extension FROM Incident	JOIN User_Acc ON user_acc.User_id=incident.user_id JOIN business ON incident.business_id=business.Business_id JOIN incident_type ON incident_type.incident_type_id = incident.incident_type_id WHERE Business.Business_Name = Business.Business_Name AND Incident.FileName=@FileName", conn);
                         comm.Parameters.Add("@FileName", System.Data.SqlDbType.VarChar).Value = e.CommandArgument;
                        conn.Open();
                        SqlDataReader reader = comm.ExecuteReader();
                        while (reader.Read())
                        {
                          ext = reader["File_Extension"].ToString();                            
                        }
                        byte[] bts = System.IO.File.ReadAllBytes(path);
                        Response.Clear();
                        Response.ClearHeaders();
                        if (ext.Equals(".mov", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/quicktime";
                        }
                        else if (ext.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "image/jpeg";
                        }
                        else if (ext.Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "image/jpeg";
                        }
                        else if (ext.Equals(".gif", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "image/gif";
                        }
                        else if (ext.Equals(".mp2", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".mpa", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".mpe", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".mpeg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".mpg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".mpv2", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".qt", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/quicktime";
                        }
                        else if (ext.Equals(".avi", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/x-msvideo";
                        }
                        Response.WriteFile(path);
                        Response.Flush();
                        Response.End();
                        break;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);

            }
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900