您好我想知道如何在gridview中获取特定的单元格值(假设它只返回1行),这样我就可以覆盖与该单元格值相关联的db中的其他数据。我想每行数据绑定按钮,但我怎么能这样做呢?
这是我对gridview的标记:
<asp:GridView id="gvInfo" runat="server" OnRowCommand="Convert.ToInt32(e.CommandArgument);" AutoGenerateColumns="true" EmptyDataText="Sorry, No Results Found. Enter User again." Visible="true">
<Columns>
<asp:TemplateField HeaderText="Test" >
<ItemTemplate>
<asp:Button id="btnUpdate" Text="Update" runat="server" OnClick="update" Visible="false"/>
<asp:Button id="btnUpdatePin" Text="Update Pin" runat="server" OnClick="updatePin" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
我试过这个但是没有发生任何事情:
protected void update(object sender, EventArgs e)
{
int status;
string idc = gvInfo.SelectedRow.Cells[0].Text;
if (chkIsAuthorized.Checked == true)
{
status = 1;
}
else
{
status = 0;
}
string sql="UPDATE starlode_users SET isauthorized = @isauthorized WHERE idcnumber=@idcnumber;";
string cs = ConfigurationManager.ConnectionStrings ["DBCON"].ConnectionString;
using (NpgsqlConnection dbcon = new NpgsqlConnection(cs))
{
dbcon.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, dbcon))
{
cmd.Parameters.AddWithValue("@isauthoried", status);
cmd.Parameters.AddWithValue("@idcnumber", idc);
cmd.ExecuteNonQuery();
}
}
}
非常感谢任何帮助。感谢。
答案 0 :(得分:1)
添加CommandArgument ='&lt;%#Container.DataItemIndex%&gt;'在您的按钮和后面的代码中,您可以获得引发事件的行。
<asp:Button ID="btnUpdate" runat="server" Text="Update" CommandName="UpdateData" CommandArgument='<%# Container.DataItemIndex %>'/>
在您的代码隐藏中订阅gridview的row命令事件。
protected void gvInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateData")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvInfo.Rows[index];
string cellText = row.Cells[0].Text;
}
}
答案 1 :(得分:0)
点击按钮后,您可以GridViewRow
SelectedRow
点击sender
参数,以获取GridViewRow
的参考
protected void update(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gr = (btn.NamingContainer as GridViewRow);
string idc = gr.Cells[0].Text;
}