如何从DataGridView中的ComboBox获取或设置数据 [英] How to get or set data from ComboBox in DataGridView

查看:855
本文介绍了如何从DataGridView中的ComboBox获取或设置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#.net中我想在DataGridView的每个单元格中获取或设置数据到ComboBox
我该怎么办。

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

>

推荐答案

您需要使用 DataGridViewComboBoxColumn

有两种方法来填充下拉列表。您可以使用通过Items属性返回的集合手动设置,也可以通过DataSource,DisplayMember和ValueMember属性将列绑定到数据源。这与WinForms ComboBox控件相同。

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; }
}


$ b $ p

假设在设计器中添加了一个DataGridViewComboBoxColumn作为第一列,一个DataGridViewTextBoxColumn作为第二列。

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

你应该看到的是组合框有三个用户可用。 DataGridView应该有三行数据源,三个帐户,并为每个帐户选择正确的组合框值。

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.

一个资源,你会发现非常方便对于任何DataGridView开发都是 DataGridView Faq

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

这篇关于如何从DataGridView中的ComboBox获取或设置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆