如何将列表绑定到Windows中的单个datagridview列 [英] how to bind the list to single datagridview column in windows

查看:89
本文介绍了如何将列表绑定到Windows中的单个datagridview列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个未绑定的datagridview,其中包含四列.

我想将列表绑定到datagridview的第一列/单列.

如何在Windows C#中制作?

问候,
Mohana

解决方案

如果您的列表包含值而不是对象,则可以使用以下代码:

 DataGridViewRow newRow;

 foreach ( var  item  in  yourList中)
{
   newRow =  DataGridViewRow();
   newRow.Cells [ 0 ].Value = item;
   yourDataGridView.Rows.Add(newRow);
} 



另一方面,如果列表包含(引用类型)对象,则必须将列更改为DataGridViewComboBoxColumn,然后将列表中的值绑定到DataGridViewComboBoxColumn使用的comboBox控件,然后使用上面的代码.

这是将值从列表绑定到comboBox的一般方法:

 // 到DataGridViewComboBoxColumn的绑定列表
// 您必须创建KeyValuePair对象列表才能
// 将原始列表中的值正确绑定到comboBox 
List<键值对><字符串,您的对象类型>> listForBinding =  List< keyvaluepair><字符串,您的对象类型>>();
 foreach ( var  item  in  yourList中)
{
   listForBinding.Add(< string,yourobjecttype>(item.ToString(),item));
}

yourDataGridViewComboBoxColumn.DisplayMember = " ;
yourDataGridViewComboBoxColumn.ValueMember = " ;
yourDataGridViewComboBoxColumn.DataSource = listForBinding;


// 第一个块的代码在这里 


Hi All,

I have one unbound datagridview with four columns.

I want to bind the list to first column/single column in the datagridview.

How can i make in windows C#??

Regards,
Mohana

解决方案

If your list contains values and not objects you could use this code:

DataGridViewRow newRow;

foreach(var item in yourList)
{
   newRow = new DataGridViewRow(); 
   newRow.Cells[0].Value = item;
   yourDataGridView.Rows.Add(newRow);
}



On the other hand if your list contains (reference type) objects you''ll have to change your column to DataGridViewComboBoxColumn, then bind values from your list to comboBox control used by DataGridViewComboBoxColumn and then use code from above.

This is general approach for binding values from list to comboBox:

//binding list to DataGridViewComboBoxColumn
//you have to create List of KeyValuePair object in order to 
//properly bind values from original list to the comboBox
List<keyvaluepair><string,yourobjecttype>> listForBinding = new List<keyvaluepair><string,yourobjecttype>>();
foreach(var item in yourList)
{
   listForBinding.Add(new <string,yourobjecttype>(item.ToString(),item));
}

yourDataGridViewComboBoxColumn.DisplayMember = "Key";
yourDataGridViewComboBoxColumn.ValueMember = "Value";
yourDataGridViewComboBoxColumn.DataSource = listForBinding; 


//code from first block goes here


这篇关于如何将列表绑定到Windows中的单个datagridview列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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