C#按钮单击数据从文本框到数据网格视图
单击按钮时,我使用以下方法将数据从3个文本框(作为一行)传输到数据网格视图(dataGridView2):C#按钮单击数据从文本框到数据网格视图,c#,visual-studio,datagridview,C#,Visual Studio,Datagridview,单击按钮时,我使用以下方法将数据从3个文本框(作为一行)传输到数据网格视图(dataGridView2): private void button1_Click(object sender, EventArgs e) { Form1 f1 = new Form1(); DataTable dt1 = new DataTable(); f1.dataGridView2.DataSource = dt1; dt1.Columns.Add("MessageID", ty
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
DataTable dt1 = new DataTable();
f1.dataGridView2.DataSource = dt1;
dt1.Columns.Add("MessageID", typeof(string));
dt1.Columns.Add("Name", typeof(string));
dt1.Columns.Add("Number", typeof(string));
DataRow dr = dt1.NewRow();
dr["MessageID"] = IDtext.Text;
dr["Name"] = nameText.Text;
dr["Number"] = numberText.Text;
f1.dataGridView2.DataSource = dt1;
}
但是,当我单击按钮时,既没有发生错误,也没有数据传输到相关的数据网格。如何更正此问题?这是一个通用问题,您可以根据需要进行更改
protected void Button1_Click(object sender, EventArgs e) {
string str = txtname.Text.Trim();
string str1 = TextBox1.Text.Trim();
dt = (DataTable) ViewState["Details"];
dt.Rows.Add(str, str1);
ViewState["Details"] = dt;
GridView1.DataSource = dt;
GridView1.EmptyDataText = "Name";
GridView1.EmptyDataText = "Address";
GridView1.DataBind();
}
创建datarow后,需要将其添加到datatable中
DataTable dt1 = new DataTable();
DataRow dr = dt1.NewRow();
dr["MessageID"] = IDtext.Text;;
dr["Name"] = nameText.Text;
dr["Number"] = numberText.Text;
dt1.Rows.Add(dr);
为什么要创建
表单的新实例
,为什么要多次设置GridView
数据源
?不要使用ViewState,这里不需要它。我面临的问题是每次按下按钮时出现“新建”对话框,数据网格中以前显示的数据都会被删除!我怎样才能克服这个问题?