Question

I have the following GridView:

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="SysInvoiceID" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="SysInvoiceID" HeaderText="SysInvoiceID" ReadOnly="True" SortExpression="SysInvoiceID" />
                <asp:BoundField DataField="BillMonth" HeaderText="BillMonth" SortExpression="BillMonth" />
                <asp:BoundField DataField="InvoiceDate" HeaderText="InvoiceDate" ReadOnly="True" SortExpression="InvoiceDate" />
                <asp:BoundField DataField="InvoiceNumber" HeaderText="InvoiceNumber" SortExpression="InvoiceNumber" />
                <asp:BoundField DataField="Net" HeaderText="Net" SortExpression="Net" />
                <asp:BoundField DataField="VAT" HeaderText="VAT" SortExpression="VAT" />
                <asp:BoundField DataField="Gross" HeaderText="Gross" SortExpression="Gross" />
                <asp:ButtonField CommandName="ViewInvoice"  HeaderText=" " ShowHeader="True" Text="View" />
            </Columns>
        </asp:GridView>

Here is the code behind the page:

public partial class PagingTest01 : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}

void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    // If multiple buttons are used in a GridView control, use the
    // CommandName property to determine which button was clicked.
    if (e.CommandName == "ViewInvoice")
    {
        // Convert the row index stored in the CommandArgument
        // property to an Integer.
        int index = Convert.ToInt32(e.CommandArgument);

        // Retrieve the row that contains the button clicked 
        // by the user from the Rows collection.
        GridViewRow row = GridView1.Rows[index];
        // Now you have access to the gridviewrow.

        ViewButton_Click(row);
    }
}




protected void ViewButton_Click(GridViewRow row)
{ 
    byte[] FileImage = GetImageData(0,row);

      if (FileImage != null)
      {
          base.Response.Clear();
          base.Response.Buffer = true;
          base.Response.ContentType = "Application/x-pdf";
          base.Response.ContentEncoding = Encoding.Default;
          string attachment = string.Format("attachment;filename=\"Invoice_{0}.pdf\"", "Customer1");
          base.Response.AddHeader("content-disposition", attachment);
          base.Response.BinaryWrite(FileImage);
          base.Response.Flush();
          base.Response.Close();
          base.Response.End();
      }
}





public byte[] GetImageData(int sysInvoiceID,  GridViewRow row)
    {

        string strUserID = CommonCode.GetCurrentUserID().ToString();
        string strCustomerID = CommonCode.GetCurrentCustomerID().ToString();
        byte[] numArray;

        string strConnectionString = "Data Source=TESTSERV;Initial Catalog=DB_Invoices;Persist Security Info=True";
        SqlConnection connection = new SqlConnection(strConnectionString);
        SqlCommand command = new SqlCommand("select FileImage from DB_Invoices.dbo.Bills WHERE (FileType = 'PDF' AND SysInvoiceID = @ID)", connection);
        command.Parameters.AddWithValue("@ID", GridView1.Rows[row].Cells[0].Text);

        SqlDataAdapter da = new SqlDataAdapter(command);
        DataSet ds = new DataSet();

        try
        {
            connection.Open();



            da.Fill(ds);
            DataRow item = ds.Tables[0].Rows[0];
            byte[] item1 = (byte[])item["FileImage"];
            ds.Tables.Clear();
            numArray = item1;


        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
        }
        return numArray;
    }



}

So basically I have a GridView with a lot of rows, each one with a 'View' Buttonfield next to it. When 'View' is clicked, I attempted to make use of GridView1_RowCommand which should hopefully grab the row clicked before passing it onto ViewButton_Click. This will then call GetImageData and pass the row number onto this line:

command.Parameters.AddWithValue("@ID", GridView1.Rows[row].Cells[0].Text);

Cell 0 is the SysInvoiceID column, so if the correct row is passed, @ID will be assigned a SysInvoiceID.

'Row' however doesn't seem to be a valid argument, though I can't think why not... Unless I have to explicitly convert it into a int? Any help would be really appreciated! Thanks.

Was it helpful?

Solution

I have just commented this as side-note but maybe it's your issue because you mention that "it doesn't seem to be a valid argument, though I can't think why not... Unless I have to explicitly convert it into a int".

If ID is an int you should use int.Parse(celltext), othwerwise the database gets the wrong type since AddWithValue needs to infer the type from the value.

So use:

command.Parameters.AddWithValue("@ID", int.Parse(GridView1.Rows[row].Cells[0].Text));

Apart from that, you haven't added the event handler GridView1_RowCommand.

<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" runat="server" AutoGenerateColumns="False" DataKeyNames="SysInvoiceID" DataSourceID="SqlDataSource1">
   ....

and you are also not setting the CommandArgument to the index of the row. I would use a different approach anyway if you need the row-index. Use a templatefield and a control, for example a Button. Then use it's NamingContainer property to get the reference to the 'GridViewRow`, here is an example: Get Row Index on Asp.net Rowcommand event

OTHER TIPS

use this:

int index = ((GridViewRow)((WebControl)sender)).RowIndex;

in place of

int index = Convert.ToInt32(e.CommandArgument);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top