选择行后获取单元格值

时间:2009-10-06 05:55:24

标签: c# asp.net gridview

我有一个Gridview,其值为MachineGroupID,MachineGroupName,MachineGroupDesc等。

我在gridview中有一个删除命令,当我点击时应该删除所选行。

现在我有一个代码告诉我选择了哪一行。

 protected void LinkButton1_Click(object sender, EventArgs e)
 {
        LinkButton btn = (LinkButton)sender;
        GridViewRow row = (GridViewRow)btn.NamingContainer;
        string machineID = (String)GridView1.SelectedValue;
        if (row != null)
        {
            LinkButton LinkButton1 = (LinkButton)sender;

            // Get reference to the row that hold the button
            GridViewRow gvr = (GridViewRow)LinkButton1.NamingContainer;

            // Get row index from the row
            int rowIndex = gvr.RowIndex;
            string str = rowIndex.ToString();
            //string str = GridView1.DataKeys[row.RowIndex].Value.ToString();
            RemoveData(str); //call the delete method
       }
 }

我想让行中的MachineGroupID出现,以便我可以传递该值并从数据库和gridview中删除记录?

由于

4 个答案:

答案 0 :(得分:2)

尝试这个.........

((Label)grd.Rows[e.RowIndex].Cells[0].FindControl("lblID")).Text

OR最好是RowCommand

protected void grdCountry_RowCommand(object sender, GridViewCommandEventArgs e)
{
    grd.DataKeys[0] // this will return the MachineGroupID
}

答案 1 :(得分:0)

GridView有一个SelectedDataKey属性,可以为您提供所需的属性(确保GridView的DataKeyNames属性设置为MachineGroupID)

答案 2 :(得分:0)

将网格的 MachineGroupID 设置为 DataKeyName DataKeyName="MachineGroupID"并通过

获取

GridView1.DataKeys[rowIndex].ToString()根据您的代码。

另一种方法是将MachineGroupID值设置为Gridview Itemtemplate中的hiddenfield 并在LinkBut​​ton1_Click事件的代码隐藏中编写以下代码:

protected void LinkButton1_Click(object sender, EventArgs e)
 {
LinkButton btn = (LinkButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
string machineID = (String)GridView1.SelectedValue;
if (row != null)
{
LinkButton LinkButton1 = (LinkButton)sender;
// Get reference to the row that hold the button
GridViewRow gvr = (GridViewRow)LinkButton1.NamingContainer;
HiddenField hdn=(HiddenField)gvr.FindControl("hdn");
// get the value of MachineGroupID for the row.
string mcgID= hdn.value;

//--------- Write delete code here-------//
 }
 }

答案 3 :(得分:0)

有很多方法可以做到这一点 - 这是一个

我有一个用于删除的图像按钮,但您可以使用此处的链接按钮

        <asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:ImageButton ImageUrl="~/Images/delete.gif" ID="btnDelete" OnClientClick='return confirm("Are you sure you want to delete this item?")' runat="server" OnCommand="DeleteRecord" CommandArgument='<%# Bind("MachineGroupId") %>' />
            </ItemTemplate>
        </asp:TemplateField>

代码:

protected void DeleteRecord(object sender, CommandEventArgs e)
{
    Guid id = new Guid((string)e.CommandArgument);
    if (RemoveData(id))
    {

    }
}