我正在使用DataTable绑定一个网格,我正在使用两列,而GridView1中的结果是,
HostelName | HostelCode
Alpha | 1
Bravo | 2
Charlie | 3
现在我想将此HostelCode作为LinkButton用于数据库中的所有记录,以便我可以在单击LinkButton时执行进一步操作。 任何帮助?
我正在使用此代码,但它不起作用,
for (int i = 0; i < dt.Rows.Count; i++)
{
LinkButton lb = new LinkButton();
lb = (LinkButton)GridView1.SelectedRow.FindControl("lbtnSelect");
lb.Text = dt.Rows[1].ToString();
}
lbtnSelect是我的链接按钮的ID。
答案 0 :(得分:2)
您可以使用gridview和Eval函数的模板字段中的链接按钮来绑定aspx页面中链接按钮的值。
<asp:GridView runat="server" ID="gvrecords" CssClass="Gridview" DataKeyNames="HostelCode"
AutoGenerateColumns="false" HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="White"
OnRowDataBound="gvrecords_RowDataBound">
<Columns>
<asp:BoundField DataField="HostelName" HeaderText="Hostel Name" />
<asp:TemplateField HeaderText="Hostel Code">
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" runat="server" OnClick="lnkbtn_Click" Text='<%#Eval("HostelCode")'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
答案 1 :(得分:0)
ASPX代码
<asp:GridView runat="server" ID="gvrecords" CssClass="Gridview" DataKeyNames="HostelCode"
AutoGenerateColumns="false" HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="White"
OnRowDataBound="gvrecords_RowDataBound">
<Columns>
<asp:BoundField DataField="HostelName" HeaderText="Hostel Name" />
<asp:TemplateField HeaderText="Hostel Code">
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" runat="server" OnClick="lnkbtn_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS CODE
public partial class Tests : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindHostelDetails();
}
}
protected void BindHostelDetails()
{
gvrecords.DataSource = DBData();
gvrecords.DataBind();
}
protected void gvrecords_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string HostelCode = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "HostelCode"));
LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("lnkbtn");
lnkbtnresult.Text = HostelCode;
}
}
protected void lnkbtn_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
int hostelcode = Convert.ToInt32(gvrecords.DataKeys[gvrow.RowIndex].Value.ToString());
string HostelName = gvrow.Cells[0].Text;
Response.Write("<script> alert('" + "Hostel Name :"+ HostelName +" Hostel Code :"+ hostelcode + "'); </script>");
}
List<DTest> DBData()
{
List<DTest> _Dt = new List<DTest>();
_Dt.Add(new DTest { HostelName = "Alpha", HostelCode = "1" });
_Dt.Add(new DTest { HostelName = "Bravo", HostelCode = "2" });
_Dt.Add(new DTest { HostelName = "Charlie", HostelCode = "3" });
return _Dt;
}
}
public class DTest
{
public string HostelName { get; set; }
public string HostelCode { get; set; }
}