无法从GridView获取行号

时间:2013-10-29 10:05:12

标签: c# asp.net gridview gridviewrow

我有以下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>

以下是页面背后的代码:

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;
    }



}

所以基本上我有一个包含很多行的GridView,每个行旁边都有一个“View”Buttonfield。单击“查看”时,我尝试使用GridView1_RowCommand,希望在将其传递到ViewButton_Click之前抓取单击的行。然后,这将调用GetImageData并将行号传递到此行:

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

单元格0是SysInvoiceID列,因此如果传递了正确的行,则会为@ID分配一个SysInvoiceID。

'Row'然而似乎不是一个有效的参数,虽然我想不出为什么不...除非我必须明确地将它转换为int?任何帮助将非常感激!谢谢。

2 个答案:

答案 0 :(得分:2)

我刚刚将此评论为旁注,但也许这是你的问题,因为你提到“它似乎不是一个有效的论点,尽管我想不出为什么不...除非我必须明确地将其转换为int“

如果IDint,则应使用int.Parse(celltext),否则数据库会出错,因为AddWithValue需要从值中推断出类型。

所以使用:

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

除此之外,您还没有添加事件处理程序GridView1_RowCommand

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

并且您也没有将CommandArgument设置为行的索引。如果你需要行索引,我会使用不同的方法。使用模板字段和控件,例如Button。然后使用它的NamingContainer属性来获取对'GridViewRow`的引用,这是一个示例:Get Row Index on Asp.net Rowcommand event

答案 1 :(得分:1)

使用它:

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

取代

int index = Convert.ToInt32(e.CommandArgument);
相关问题