[英]insert into gridview from textbox.text
I have a gridview control and I want to input a value to a textbox and click button so that it inserts a value from textbox.text to the gridview. 我有一个gridview控件,我想向文本框输入一个值,然后单击按钮,以便它将textbox.text中的一个值插入到gridview中。 I use this code:
我使用以下代码:
<asp:TextBox ID="txtName" runat="server" ViewStateMode="Enabled"></asp:TextBox>
<br />
<asp:Button ID="btnAddName" runat="server" Text="Button"
onclick="btnAddName_Click" />
<br />
<br />
<asp:GridView ID="gvName" runat="server" ViewStateMode="Enabled">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and: 和:
protected void btnAddName_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("lblName", typeof(string)));
DataRow _dr = dt.NewRow();
_dr["lblName"] = txtName.Text;
dt.Rows.Add(_dr);
gvName.DataSource = dt;
gvName.DataBind();
}
I input the text in the textbox and click on the button to insert a value to the gridview. 我在文本框中输入文本,然后单击按钮以在gridview中插入一个值。 It works ok, but on the second step, after page postback it lost previous data in the gridview.
它可以正常工作,但是在第二步中,页面回发后,它在gridview中丢失了先前的数据。
I want to not lose the previous data in the gridview. 我不想在gridview中丢失先前的数据。 Please help me.
请帮我。
You need to add row to original source you are binding to GridView
. 您需要向绑定到
GridView
原始源添加行。 if you create new table each time you click button and bind that to gridview
, it will show data from new DataTable
and old data. 如果您每次单击按钮创建新表并将其绑定到
gridview
,它将显示来自新DataTable
和旧数据的数据。
try this 尝试这个
protected void btnAddName_Click(object sender, EventArgs e)
{
DataTable dt;
if(Session["dt"] == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("lblName", typeof(string)));
}
else
{
dt = (DataTable)Session["dt"];
}
DataRow _dr = dt.NewRow();
_dr["lblName"] = txtName.Text;
dt.Rows.Add(_dr);
gvName.DataSource = dt;
gvName.DataBind();
Session["dt"] = dt;
//store dt in session so that you can reuse it again after postback
}
Are you checking in your Page_Load Method if your page is in PostBack mode? 如果页面处于回发模式,您是否正在签入Page_Load方法?
if(IsPostBack) { //Load the data for the first time }
If not, your originally and "old" data will be bind to the gridview. 如果没有,您的原始数据和“旧”数据将被绑定到gridview。
Update: To reuse the old data, store the datatable in a session variable, load it from there, add the new line and bind data datatable again. 更新:要重用旧数据,请将数据表存储在会话变量中,然后从那里加载它,添加新行并再次绑定数据数据表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.