0

The following method is used by me to transfer data from 3 text boxes(as a single row) to a data grid view(dataGridView2) when a button is clicked:

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

But when I click the button, neither an error occurs, and also no data is transferred to the relevant data grid. How can I correct this?

1
  • Why are you creating new instance of form and why you are setting GridView DataSource multiple times? Commented Aug 22, 2017 at 4:40

2 Answers 2

1

You need to add datarow to datatable after creating it.

DataTable dt1 = new DataTable();
DataRow dr = dt1.NewRow();
dr["MessageID"] = IDtext.Text;;
dr["Name"] = nameText.Text;
dr["Number"] = numberText.Text;
dt1.Rows.Add(dr);
Sign up to request clarification or add additional context in comments.

1 Comment

the problem i face is each time the new dialog box appears when i press the button previously displayed data in the data grid gets deleted! how can i overcome this?
0

This is a general one , you can change according to ur need.

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

1 Comment

Don't use ViewState , its not needed here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.