【发布时间】:2013-09-11 10:31:46
【问题描述】:
这是一个小的注册表单,我想做的就是当用户单击按钮时,我想通过使用数据表和会话将表单中的详细信息输入到网格视图中
<form id="form1" runat="server">
<div>
<center>
<table>
<tr>
<td>
First Name
</td>
<td>
<asp:TextBox ID="TxtFirstName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Last Name
</td>
<td>
<asp:TextBox ID="TxtLastName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Location
</td>
<td>
<asp:TextBox ID="TxtLocation" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Mobile No
</td>
<td>
<asp:TextBox ID="TxtMobileNo" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="BtnSave" Text="SAVE" runat="server" onclick="BtnSave_Click"/>
</td>
<td>
<asp:Button ID="BtnCancel" Text="CANCEL" runat="server" />
</td>
</tr>
</table>
</center>
<center>
<asp:GridView ID="GridDataTable" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField HeaderText="First Name" >
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name"></asp:TemplateField>
<asp:TemplateField HeaderText="Location"></asp:TemplateField>
<asp:TemplateField HeaderText="Mobile No"></asp:TemplateField>
</Columns>
</asp:GridView>
</center>
</div>
</form>
这是我的代码,但它不起作用帮助我解决这个问题
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
protected void Bind()
{
System.Data.DataTable workTable = new System.Data.DataTable("RegTable");
workTable.Columns.Add(new DataColumn("FirstName", typeof(String)));
workTable.Columns.Add(new DataColumn("LastName", typeof(String)));
workTable.Columns.Add(new DataColumn("Location", typeof(String)));
workTable.Columns.Add(new DataColumn("MobileNo", typeof(Int32)));
Session["RegDetails"] = workTable;
GridDataTable.DataSource = workTable;
GridDataTable.DataBind();
}
protected void BtnSave_Click(object sender, EventArgs e)
{
System.Data.DataTable dt = (System.Data.DataTable)Session["RegDetails"];
DataRow dr = dt.NewRow();
dr["FirstName"] = TxtFirstName.Text.ToString();
dr["LastName"] = TxtLastName.Text.ToString();
dr["Location"] = TxtLocation.Text.ToString();
dr["MobileNo"] = TxtMobileNo.Text;
dt.Rows.Add(dr);
Session["RegDetails"] = dt;
GridDataTable.DataSource = dt;
GridDataTable.DataBind();
}
【问题讨论】:
-
“它不起作用” 也许您可以稍微说明一下问题所在。顺便说一句,你为什么要添加一个没有名称和类型的
DataColumn?workTable.Columns.Add(workCol); -
我认为每一列都有它的类型和名称。有什么问题
-
究竟是什么在这里不起作用?可能是会话,请尝试使用
ViewState。这条线DataColumn workCol = new DataColumn();你在用它做什么?为什么你在这里添加一个空行DataRow dr = workTable.NewRow();? -
@Vivekh:我已经发布了没有名称和类型的
DataColumn,它是workCol。你已经用这种方式初始化了它:DataColumn workCol = new DataColumn();. -
知道它还没有将 itemtemplate 添加到 gridview。无论如何谢谢