开发者

How to get or set data from ComboBox in DataGridView

In C#.net I want to get or set data to ComboBox in each cell of DataGridView What should I do.

Tha开发者_JAVA技巧nks.


You need to use a DataGridViewComboBoxColumn.

There are two ways of populating the drop-down list. You can either set it manually by using the collection returned through the Items property or by binding the column to a data source through the DataSource, DisplayMember and ValueMember properties. This is the same as the WinForms ComboBox control.

An example of setting you data source programatically is below:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        dataGridView1.AutoGenerateColumns = false;

        List<User> users = new List<User>();
        users.Add(new User(){Name = "Fred", Id = 1});
        users.Add(new User(){Name = "Jill", Id = 2});
        users.Add(new User(){Name = "Bob", Id = 3});

        List<Account> accounts = new List<Account>();
        accounts.Add(new Account(){AccountName = "Mr Smith", UserId = 1});
        accounts.Add(new Account() { AccountName = "Ms Brown", UserId = 2 });
        accounts.Add(new Account() { AccountName = "Mr Smith 2", UserId = 1 });

        dataGridView1.DataSource = accounts;

        DataGridViewTextBoxColumn col1 = dataGridView1.Columns[1] as DataGridViewTextBoxColumn;
        col1.DataPropertyName = "AccountName";

        DataGridViewComboBoxColumn col = dataGridView1.Columns[0] as DataGridViewComboBoxColumn;
        col.DataSource = users;
        col.DisplayMember = "Name";
        col.DataPropertyName = "UserId";
        col.ValueMember = "Id";
    }

}

public class User
{
    public string Name { get; set; }
    public int Id { get; set; }
}

public class Account
{
    public string AccountName { get; set; }
    public int UserId { get; set; }
}

That assumes that in the designer you added a DataGridViewComboBoxColumn as the first column and a DataGridViewTextBoxColumn as the second column.

What you should see is that the combo box has the three users available. The DataGridView should have three rows from the data source, for the three Accounts, and the right combo box value shoud be selected for each.

A resource you will find very handy for any DataGridView development is the DataGridView Faq


First, if you have not done so already, decide how you are going to provide data to the DataGridView (Virtual mode, data binding, etc).

Then add the values the user can select to the Items collection on the column header (assuming it's a DataGridViewComboBoxColumn).

After that, set the value of the individual cells using the underlying data providing method you chose.


Try this...

private void PopulateData()
{            
   while (condition) //Columns[0] is where your ComboBoxColumn index
      (dataGridView1.Columns[0] as DataGridViewComboBoxColumn)
      .Items.Add("Item 1");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜