Mahmoud Abdelhamid
Mahmoud Abdelhamid

Reputation: 49

How can I fill a ListBox using data of a Column of a DataGridVeiw?

I have two windows forms. In the first form I have a DataGridView and search button. Wen I click search, the grid fills by data from a DataTable which is returned by a stored procedure. I to need take single column from this DataGridView and fill a Listbox in another form.
How I can fill ListBox in second form, from values of column at index 3 of first form ?

DT = rec.AdvancdSearch(txtname.Text.ToString(),int.Parse(cmblocation.SelectedValue.ToString()), cmbstatus.Text.ToString(), txtfrom.Text.ToString(), txtto.Text, cbmgendr.Text, int.Parse(cbmjob.SelectedValue.ToString()));
dataGridView1.DataSource = DT;
if (dataGridView1.Rows.Count < 2)
{
    MessageBox.Show("عذراً لم يتم العثور على اى نتائج بحث مطابقة للبينات المدخلة", "عملية البحث", MessageBoxButtons.OK, MessageBoxIcon.Information);
    lblcount.Text = "لا يوجد نتائج";
}
else
{
    lblcount.Text = "نتائج البحث \n" + (dataGridView1.Rows.Count-1);
}

Upvotes: 0

Views: 646

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125312

Get values

As an option you can select values of column at index 3 of DataGridView this way:

var list = dataGridView1.Rows.Cast<DataGridViewRow>()
                        .Where(x => !x.IsNewRow)
                        .Select(r => r.Cells[3].Value.ToString())
                        .ToList();

Also you can get values from DataTable:

var list = dt.Rows.Cast<DataRow>().Select(r => r.Field<string>(3)).ToList();

Pass Values to another Form

After getting the list, you should pass values to another form this way:

var f2 = new Form2(list);
f2.Show();

To be able to to write var f2 = new Form2(list); and pass the list to you your second form, you should change the constructor of that form to accept a value of type List<string>:

List<string> list;
public Form2 (List<string> l)
{
    InitializeComponent();
    list= l;
    this.listBox1.DataSource = list;
}

Show in ListBox

As you can see above, in second form, its enough to use:

this.listBox1.DataSource = list;

Also you can add items:

this.listBox1.Items.AddRange(list.ToArray());

Upvotes: 1

Related Questions