如何在单击按钮时在GridView中显示通过TextBox输入的值,而不将数据保存到数据库中
本文关键字:数据 数据库 保存 TextBox 按钮 单击 GridView 显示 输入 | 更新日期: 2023-09-27 17:59:32
我创建了两个文本框,用于输入员工的FirstName和LastName以及基于web的ASP中的一个按钮。NET应用程序。当我单击按钮时,我在TextBoxes中输入的值应该显示在Gridview中,而不是存储在数据库中。
我该怎么做?您能提供一个执行上述功能的示例代码吗?
这是一个工作代码。。
protected void Page_Load(object sender, EventArgs e)
{
dt = new DataTable();
DataColumn dc1 = new DataColumn("FIRST NAME");
DataColumn dc2 = new DataColumn("LAST NAME");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
DataRow dr1 = dt.NewRow();
GridView1.DataSource = dt;
GridView1.DataBind();
}
DataTable dt;
protected void Button1_Click(object sender, EventArgs e)
{
DataRow dr1 = dt.NewRow();
dr1[0] = TextBox1.Text;
dr1[1] = TextBox2.Text;
dt.Rows.Add(dr1);
GridView1.DataSource = dt;
GridView1.DataBind();
}
您可以用以下代码访问gridview:
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
在您可以访问该网格视图后,将有续订/添加/删除客户端信息的方法。但请注意,您还必须告诉服务器端您续订了数据库中的信息,这样他就可以将更改保存到数据库中
我希望您应该发送ajax请求在DB中续订数据,并使用代码从javascript访问网格,并通过javascript在客户端续订数据。
取您在DataTable中的文本框中输入的值,并将该数据表作为数据源提供给datagrid
检查此链接http://forums.asp.net/t/1672122.aspx/1
您提供的代码运行良好。但它将只向GridView添加一条记录。如果添加了新记录,则旧数据将被替换。所以我们必须保留旧的记录。
只需在按钮点击事件中输入以下代码。
protected void Button1_Click(object sender, EventArgs e)
{
if(Session["Data"] == null) //Checking if the session contain any value.
{
DataTable dt = new DataTable(); //creating the columns.
dt.Columns.Add("Name");
dt.Columns.Add("Price");
dt.Columns.Add("Stock");
DataRow dr = dt.NewRow(); //Create a new row and add the row values.
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dr[2] = TextBox3.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt; //Populate values to Gridview.
GridView1.DataBind();
Session["Data"] = dt; //Storing that table into session.
}
else
{
DataTable dt = new DataTable();
dt = (DataTable)Session["Data"]; //Retrieve the stored table from session.
DataRow dr = dt.NewRow(); //Adding a new row to existing table.
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dr[2] = TextBox3.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt; //Populate new table values to Gridview.
GridView1.DataBind();
Session.Remove("Data"); //Clear the session.
Session["Data"] = dt; //Store the new table to the session.
}
}
private int id = 0;
private void dataGridView1_CellClick(object sender,
DataGridViewCellEventArgs e)
{
int RowIndex = e.RowIndex;
id= Convert.ToInt32(dataGridView1.Rows[RowIndex].Cells[0].Value.ToString());
textBox1.Text = dataGridView1.Rows[RowIndex].Cells[1].Value.ToString();
textBox2.Text = dataGridView1.Rows[RowIndex].Cells[2].Value.ToString(); textBox3.Text = dataGridView1.Rows[RowIndex].Cells[3].Value.ToString();
textBox4.Text = dataGridView1.Rows[RowIndex].Cells[4].Value.ToString();
}