我正尝试在按下按钮时在GridView
中创建一个新行,其值为labels
:
<Asp:Label id="Label1" runat="Server" Text="My name">
<Asp:Label id="Label2" runat="Server" Text="My Age">
<Asp:Label id="Label3" runat="Server" Text="My Gender">
以下GridView
包含Label
TemplateFields
<Asp:Gridview runat="Server" Id="GridView1" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label runat="server" ID="Name_lbl" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label runat="server" ID="Age_lbl" Text='<%# Eval("Age")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:Label runat="server" ID="Gender_lbl" Text='<%# Eval("Gender")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
在Button_Click
中,Label
值将插入到gridview中。
我的尝试将Label
值插入GridView
但我收到错误:"DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Name'"
DataTable dt = new DataTable();
DataRow dr;
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(string));
dt.Columns.Add("Gender", typeof(string));
}
foreach (GridViewRow gvr in GridView1.Rows)
{
dr = dt.NewRow();
Label1.Text =( gvr.FindControl("Name_lbl") as Label).ToString();
Label2.Text = (gvr.FindControl("Age_lbl") as Label).ToString();
Label3.Text = (gvr.FindControl("Gender_lbl") as Label).ToString();
dr[1] = Label1.Text;
dr[2] = Label2.Text;
dr[3] = Label3.Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();