网格视图按钮通过单击传递数据

时间:2010-06-16 12:37:40

标签: c# asp.net gridview

我对C#和asp.net很陌生,如果这是一个非常愚蠢的问题,请道歉。

我正在使用网格视图来显示数据库中的大量记录。

每一行都有一个编辑按钮。单击该按钮时,我希望将ID传递回我的.cs文件中的函数。如何将rowID绑定到Button字段?

我已经厌倦了使用超级链接,但这似乎不起作用,因为我回发到已经在URL上已经有Permanter的同一页面。

asp.net

<asp:GridView ID="gvAddresses" runat="server" onrowcommand="Edit_Row">
    <Columns>
        <asp:ButtonField runat="server" ButtonType="Button" Text="Edit">
    </Columns>
</asp:GridView>

C#

        int ImplantID = Convert.ToInt32(Request.QueryString["ImplantID"]);
        Session.Add("ImplantID", ImplantID);

        List<GetImplantDetails> DataObject = ImplantDetails(ImplantID);

        System.Data.DataSet DSImplant = new DataSet();
        System.Data.DataTable DTImplant = new DataTable("Implant");

        DSImplant.Tables.Add(DTImplant);

        DataColumn ColPostCode = new DataColumn();
        ColPostCode.ColumnName = "PostCode";
        ColPostCode.DataType = typeof(string);
        DTImplant.Columns.Add(ColPostCode);

        DataColumn ColConsigneeName = new DataColumn();
        ColConsigneeName.ColumnName = "Consignee Name";
        ColConsigneeName.DataType = typeof(string);
        DTImplant.Columns.Add(ColConsigneeName);

        DataColumn ColIsPrimaryAddress = new DataColumn();
        ColIsPrimaryAddress.ColumnName = "Primary";
        ColIsPrimaryAddress.DataType = typeof(int);
        DTImplant.Columns.Add(ColIsPrimaryAddress);

        DataColumn ColImplantCustomerDetailsID = new DataColumn();
        ColImplantCustomerDetailsID.ColumnName = "Implant ID";
        ColImplantCustomerDetailsID.DataType = typeof(int);
        DTImplant.Columns.Add(ColImplantCustomerDetailsID); 

        foreach (GetImplantDetails Object in DataObject)
        {

            DataRow DRImplant = DTImplant.NewRow();
            DRImplant["PostCode"] = Object.GetPostCode();
            DRImplant["Consignee Name"] = Object.GetConsigneeName();
            DRImplant["Primary"] = Object.GetIsPrimaryAddress();
            DRImplant["Implant ID"] = Object.GeTImplantCustomerDetailsID();
            DTImplant.Rows.Add(DRImplant); <--- this is what I need to be added to the button

        }

        gvAddresses.DataSource = DTImplant;
        gvAddresses.DataBind(); 

1 个答案:

答案 0 :(得分:2)

Edit_Row方法中,您可以访问正在编辑的行的索引,如:

int rowIndex = (int)e.CommandArgument;

完成后,您可以直接访问该行并提取所需的任何值:

GridViewRow row = gvTest.Rows[rowIndex];
int implantId = Int32.Parse(string row.Cells[3].Text);

或者,您也可以将属性DataKeyNames="Implant ID"添加到GridView并以这种方式访问​​ID:

int implantId = Int32.Parse(gvTest.DataKeys[rowIndex]["Implant ID"].ToString());