我有一个带有按钮的gridview。我希望每行上的按钮获取每行的gridview中第一个单元格的值。例如,下表:
|标题1 |标题2 |标题3 |
|快乐|伤心|按钮1 |
|担心|生气|按钮2 |
|兴奋|皱眉|按钮3 |
当我按下按钮1时,它将显示Happy。如果我按下按钮2,它将显示忧虑。等等等等。需要你的帮助我如何实现这一目标。
.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";
}
}
}
答案 0 :(得分:2)
添加CommandArgument =&#39;&lt;%#Container.DataItemIndex%&gt;&#39;在您的按钮和后面的代码中,您可以获得引发事件的行。
<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;
}
}
答案 1 :(得分:0)
protected void btnSendInvite_OnClick(object sender,EventArgs e)
{
Button btn=(Button)sender;
GridViewRow row=(GridViewRow)btn.NamingContainer;
string name=row.Cells[1].Text; // here you will get Name
}