I would like the data from column 2 (all rows) in a DataGridView to be the input for a combobox in another form. The code below that I've tried contains 2 errors comboBox1 does not exist in current context and object reference is required for non-static field. Below is my code.
Form 1 (with a DataGridView and button)
// put as public string as the DataGridView rows will keep updating
public string data;
public Form1()
{
InitializeComponent();
}
//button to go Form 2 which contains the combobox
private void Button1_Click(object sender, EventArgs e)
{
string data = string.Empty;
int indexOfYourColumn = 2;
foreach (DataGridViewRow row in dataGridView1.Rows)
data = row.Cells[indexOfYourColumn].Value.ToString();
comboBox1.Items.Add(data);
this.Hide();
FormsCollection.Form2.Show();
}
Form2 (with combobox)
//put as public to obtain value from Form 1
public string data;
public Form 2()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.Text = Form1.data;
//not to repeat the value entered if a particular value has been entered
String s = data;
if (!comboBox1.Items.Contains(s))
{
comboBox1.Items.Add(s);
}
}
When you want to pass a collection of informations you need to use an appropriate type. For example a List<string>
not a simple string. Then you create or get the instance of the second form and only after you have an instance of your second form you can give it the collection of data to display
private void Button1_Click(object sender, EventArgs e)
{
// These is where you store the elements to pass to the Form2 instance
List<string> data = new List<string>();;
int indexOfYourColumn = 2;
// Build the collection from the selected column for each row
foreach (DataGridViewRow row in dataGridView1.Rows)
data.Add(row.Cells[indexOfYourColumn].Value.ToString());
this.Hide();
// pass your data to the public property of the Form2 instance
Form2 f = FormsCollection.Form2;
f.Data = data;
f.Show();
}
As you can see the data value is passed to the second instance through a public property and in the set accessor of that property you change the content of the internal combobox1
private List<string> _data;
public List<string> Data
{
get { return _data; }
set
{
_data = value;
// This code uses the DataSource property of the combobox
// combobox1.DataSource = null;
// combobox1.DataSource = value;
// This code works directly with the Items collection of the combo
combobox1.Items.Clear();
foreach(string s in _data)
combobox1.Items.Add(s);
}
};
public Form 2()
{
InitializeComponent();
}
...