问题描述
我想将一个组合框的数据源设置为表的一列,而此组合框是gridview列之一,我的代码是:
i want to set data source of one combo box to one column of table and this combo box is one of gridview column my code is :
DataTable p = new System.Data.DataTable();
p = selectcolor();
(dataGridView1.Columns[4] as DataGridViewComboBoxColumn).DataSource = p;
private DataTable selectcolor()
{
DataTable k = new System.Data.DataTable();
try
{
string str = "Data Source=C:\\Documents and Settings\\almas\\Desktop\\BazarKhodro\\khodro.sdf";
Qconnection.ConnectionString = str;
Qcommand.Connection = Qconnection;
string commandText = "select color from foroosh";
Qcommand.CommandText = commandText;
Qcommand.CommandType = CommandType.Text;
SqlCeDataAdapter a = new SqlCeDataAdapter();
a.SelectCommand = Qcommand;
a.Fill(k);
Qconnection.Open();
Qconnection.Close();
return k;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
return k;
}
}
运行后,我看到p的内容,但0出现此错误
对象引用未设置为对象的实例.
请帮助我
after runing i see the content of p but 0ccur this error
Object reference not set to an instance of an object.
pls help me
推荐答案
(dataGridView1.Columns[4] as DataGridViewComboBoxColumn).DataSource
http://msdn.microsoft.com/en-us/library/cscsdfbt%28v = vs.71%29.aspx [ ^ ]
如果这种类型的转换不起作用,它只会返回null,因此您试图在一个null对象上设置.DataSource
属性.
我不能说为什么强制转换不起作用,但是在强制转换之前,您需要检查dataGridView1.Columns[4]
不为空,并且dataGridView1.Columns[4]
是DataGridViewComboBoxColumn
类型.
http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx[^]
If this type of cast doesn''t work, it simply returns null, so you''re trying to set the .DataSource
property on an object that is null.
I can''t say why the cast isn''t working but you need to check that dataGridView1.Columns[4]
is not null and that dataGridView1.Columns[4]
is of type DataGridViewComboBoxColumn
before you cast.
这篇关于将数据从表复制到组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!