我有带有按钮的 gridview。我希望每行上的按钮获取每行 gridview 中第一个单元格的值。例如下表:
|标题 1 |标题 2 | header 3 |
|快乐 |悲伤 |按钮 1 |
|担心 |生气 |按钮 2 |
|兴奋 |皱眉 |按钮 3 |
当我按下按钮 1 时,它会显示 Happy。如果我按下按钮 2,它会显示 Worry。等等等等。需要您帮助我如何实现这一目标。
.HTML
<asp:gridview id="grdCreateGroup" runat="server" DataKeyNames="id" AutoGenerateColumns="false" OnRowCommand="grdCreateGroup_RowCommand" OnRowDataBound="grdCreateGroup_RowDataBound">
<Columns>
<asp:BoundField DataField="admissionNo" HeaderText="Admission No." />
<asp:BoundField DataField="fullName" HeaderText="Full Name" />
<asp:templatefield headertext="">
<itemtemplate>
<asp:Button ID="btnSendInvite" runat="server" Text="Send Invite" CommandName="sendInvite" />
</itemtemplate>
</asp:templatefield>
</Columns>
</asp:gridview>
.CS
protected void grdCreateGroup_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "sendInvite")
{
account accounta = new account();
account accountb = new account();
accountManager accountManager = new accountManager();
invite invite = new invite();
inviteManager inviteManager = new inviteManager();
string emailAddress, admissionNo;
bool status = true;
emailAddress = HttpContext.Current.User.Identity.Name;
accounta = accountManager.getAccInfoByEmailAddress(emailAddress);
invite.leaderName = accounta.fullName;
invite.groupNo = accounta.groupNo;
//invite.recipientEmailAddress = accountb.recipientEmailAddress;
//status = inviteManager.sendInvite(invite);
GridViewRow Row = grdCreateGroup.Rows[0];
Button btnSendInvite = (Button)Row.FindControl("btnSendInvite");
if (status == true)
{
divMessage.InnerHtml = invite.groupNo.ToString();
btnSendInvite.Text = "Invite Sent";
btnSendInvite.Enabled = false;
}
else
{
divMessage.InnerHtml = "Record not added in database";
}
}
}
最佳答案
将 CommandArgument='<%# Container.DataItemIndex %>' 添加到您的按钮,在您后面的代码中您可以获得引发事件的行。
<asp:Button ID="btnSendInvite" runat="server" Text="Send Invite" CommandName="sendInvite" CommandArgument='<%# Container.DataItemIndex %>'/>
获取代码后面的行
protected void grdCreateGroup_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "sendInvite")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = grdCreateGroup.Rows[index];
Button b = (Button)row.FindControl("btnSendInvite");
b.Text = row.Cells[0].Text;
}
}
关于C# 获取按钮单击 gridview 上每一行的单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31243078/