Added multiple items in a Datagrid by List<>

Asked

Viewed 197 times

1

I have two textbox. One for email and the other for notes. When the user clicks on the add button, it should be adding to my datagrid, but without success! How can I do this? As the user clicks on the add button, he has to increase the datagrid lines

Note: Using WPF

This is how I try:

public class Email{

     public string email { get; set; }
     public string obs { get; set; }
    }

for (int i=0; i < 10; i++){

     List<Email> lista = new List<Email>();
     Email em = new Email();
     em.email = textEmpEmail.Text;
     em.obs = textEmpObs1.Text;
     lista.Add(em);

     dataGridEmails.ItemsSource = lista;
}

That way, it inserts 10 at a time... But I needed it to add per click, one at a time..

Thank you!

1 answer

1

You can add the values as follows.

 dataGridView1.Rows.Add();
 dataGridView1.Rows[dataGridView1.Rows.Count-1].Cells[0].Value = textBox1.Text;
 dataGridView1.Rows[dataGridView1.Rows.Count-1].Cells[1].Value = textBox2.Text;

Now if you want to add the whole list at once, create the columns on your grid with "Datapropertyname" equal to the name of the properties of your class and pass this way.

 List<Email> lista = new List<Email>();
 Email em = new Email();
 em.email = textBox1.Text;
 em.obs = textBox2.Text;
 lista.Add(em);

 dataGridView1.DataSource = lista;
  • So, but I don’t know how many times the user will try to add the emails. Note: I am used WPF

Browser other questions tagged

You are not signed in. Login or sign up in order to post.