So i have a datagridview which is populated with a list of objects. I added on the form 3 textboxes and a button. The question is how to insert and populate another row into the datagridview with the text from textboxes.
this is my class:
class Professor
{
private int id;
private string name;
private double salary;
public Professor()
{
this.id= 0;
this.name = null;
this.salary= 0;
}
public Professor(int m, string n, double s)
{
this.id= m;
this.name = n;
this.salary= s;
}
}
This is the declaration for the list:
ArrayList listProfessors = new ArrayList();
This is the button which populates the DataGridView:
private void addInGridViewFromList_Click(object sender, EventArgs e)
{
string linie;
System.IO.StreamReader file= new System.IO.StreamReader("D:\\Profesor\\Profesor\\Profesori.txt");
while ((line= file.ReadLine()) != null)
{
string[] t = line.Split(',');
listProfessors .Add(new Professor(Convert.ToInt32(t[0]), t[1], Convert.ToDouble(t[2])));
}
file.Close();
dataGridView1.DataSource = listProfessors ;
}
And here on this button i want to add another row manually(using texboxes) into the DataGridView.
private void AddFromKeyboard_Click(object sender, EventArgs e)
{
}
You need to create a button event that do what you want, and when the button pressed you add a new row with the textboxes you want.
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Add(textBox1.Text, textBox2.Text, textBox3.Text);
}
edit: So try to add a new item to your list from the button:
private void AddFromKeyboard_Click(object sender, EventArgs e)
{
listProfessors.Add(new Professor(Convert.ToInt32(textBox1.Text), textBox2.Text, Convert.ToDouble(textBox3.Text)));
}
Before anything you should provide us a little bit of your code where you are doing some stuffs, but without it also I will try to explain it to you,
first of all what you might do is next: check is your datagrid's source some list, so you might create an corresponding object from a your textbox and you might simply add it to your list which is source to datagrid and simply refresh the source like:
dataGrid.ItemsSource=null;
dataGrid.ItemsSource = myCustomList;
Or you might do something like this:
private void btnAdd_Click(object sender, EventArgs e)
{
string firstColum = firstTextBox.Text;
string secondColum = secondTextBox.Text;
string[] row = { firstColum, secondColum };
yourDatagrid.Rows.Add(row);
}
But I'm saying again for fully correct answer you should provide / post your code.
Whatever I hope that this will help you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.