0

I have an GridView with button "Delete". I need get value to column or cell of index[3]. But with GridView1.SelectedRow.Cells[3].Text; it return null. Someone help me? I do not want use javascript.

My aspx:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" GridLines="None"
        CssClass="table table-bordered table-striped">
        <Columns>
            <asp:BoundField DataField="DisplayName" HeaderText="Display Name" />
            <asp:BoundField DataField="UserName" HeaderText="User Name" />
            <asp:BoundField DataField="Email" HeaderText="Email" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_OnClick" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

My .cs:

protected void btnDelete_OnClick(object sender, EventArgs e)
{
    using (objConexao = new SqlConnection(strStringConexao))
    {
        SqlConnection oConn = new SqlConnection();
        SqlCommand oCommand = new SqlCommand();
        string strConn = ConfigurationManager.ConnectionStrings["XXX"].ConnectionString;
        oConn.ConnectionString = strConn;
        oCommand.Connection = oConn;
        oCommand.CommandText = "proc_Delete";
        oCommand.CommandType = CommandType.StoredProcedure;

        SqlParameter myParam = oCommand.Parameters.Add("@UserRequestor", SqlDbType.NVarChar);
        myParam.Value = User;

        SqlParameter myParam2 = oCommand.Parameters.Add("@UserName", SqlDbType.NVarChar);
        myParam2.Value = GridView1.Columns[3].ToString();

        oConn.Open();
        oCommand.ExecuteNonQuery();
        oConn.Close();
    }
}
4

2 回答 2

2

尝试这个:

protected void btnDelete_OnClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    GridViewRow row = (GridViewRow)btn.NamingContainer
    string desiredText = row.Cells[3].Text;
    using (objConexao = new SqlConnection(strStringConexao))
    {
        // ...
        myParam2.Value = desiredText;
        // ...
    }        
}

NamingContainer将为您Button提供被点击的行

我认为该SelectedRow属性不起作用,因为单击按钮并不构成选择行。这是通过CommandName="Select"一个按钮完成的,或者AutoGenerateSelectButton="true"在你的GridView. 这个问题提供了一个解释。

于 2013-07-24T18:34:14.580 回答
0

已经有一段时间了,但我知道您可以为此使用 datakeynames。

在标记中为您要访问的任何值添加一个键

<asp:GridView ID="GridView1" DataKeyNames="Email" runat="server" AutoGenerateColumns="false" GridLines="None"
    CssClass="table table-bordered table-striped">

然后您应该能够使用行索引来获取值。

GridView1.DataKeys[3].Value.ToString()

已经有一段时间了,所以你可能不得不玩这个。

这是一篇包含更多信息的文章,以及如何拥有多个数据键

于 2013-07-24T18:39:16.827 回答