簡體   English   中英

C#按鈕從文本框中單擊數據到數據網格視圖

[英]C# button click datafrom textboxes to a data grid view

單擊按鈕時,我使用以下方法將數據從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", 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;
}

但是,當我單擊按鈕時,既不會發生錯誤,也不會有數據傳輸到相關的數據網格。 我該如何糾正?

創建數據行后,需要將其添加到數據表中。

DataTable dt1 = new DataTable();
DataRow dr = dt1.NewRow();
dr["MessageID"] = IDtext.Text;;
dr["Name"] = nameText.Text;
dr["Number"] = numberText.Text;
dt1.Rows.Add(dr);

這是一般情況,您可以根據需要進行更改。

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();  
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM