C# 哈希表datagridview显示空行
我的Datagrid中填充了正确数量的行,但没有显示数据。 所有行都显示空列 原因可能是什么 这是我第一次使用datagridviewC# 哈希表datagridview显示空行,c#,datagridview,hashtable,C#,Datagridview,Hashtable,我的Datagrid中填充了正确数量的行,但没有显示数据。 所有行都显示空列 原因可能是什么 这是我第一次使用datagridview public void BindDataGridView(DataGridView dgv, Hashtable ht) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add("test"); //now build our table
public void BindDataGridView(DataGridView dgv, Hashtable ht) {
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("test");
//now build our table
dt.Columns.Add("col1", typeof(string));
dt.Columns.Add("col2", typeof(Int32));
IDictionaryEnumerator enumerator = ht.GetEnumerator();
DataRow row = null;
while (enumerator.MoveNext()) {
string index = (string)enumerator.Key; // boekingsREf
MyClass a = (MyClass)enumerator.Value;
row = dt.NewRow();
row["col1"] = index;
row["col2"] = a.number;
dt.Rows.Add(row);
}
//dgv.DataSource = ds.Tables[0];
dgv.DataSource = ds.Tables[0];
}
第一个示例:
public Form1()
{
InitializeComponent();
Hashtable ht = new Hashtable();
ht[1] = "One";
ht[2] = "Two";
ht[3] = "Three";
BindDataGridView(dataGridView1, ht);
}
public void BindDataGridView(DataGridView dgv, Hashtable ht)
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("test");
//now build our table
dt.Columns.Add("col1", typeof(int));
dt.Columns.Add("col2", typeof(string));
foreach (DictionaryEntry dictionaryEntry in ht)
{
int index = (int)dictionaryEntry.Key;
string value = (string)dictionaryEntry.Value;
DataRow row = dt.NewRow();
row["col1"] = index;
row["col2"] = value;
dt.Rows.Add(row);
}
dgv.DataSource = ds.Tables[0];
}
第二个示例:
public Form1()
{
InitializeComponent();
Hashtable ht = new Hashtable();
ht[1] = "One";
ht[2] = "Two";
ht[3] = "Three";
BindDataGridView(dataGridView1, ht);
}
public void BindDataGridView(DataGridView dgv, Hashtable ht)
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("test");
//now build our table
dt.Columns.Add("col1", typeof(int));
dt.Columns.Add("col2", typeof(string));
foreach (DictionaryEntry dictionaryEntry in ht)
{
int index = (int)dictionaryEntry.Key;
string value = (string)dictionaryEntry.Value;
DataRow row = dt.NewRow();
row["col1"] = index;
row["col2"] = value;
dt.Rows.Add(row);
}
dgv.DataSource = ds.Tables[0];
}
假设您的MyClass
是
public class MyClass
{
public int number { get; set; }
static public implicit operator MyClass(int value)
{
return new MyClass() { number = value };
}
}
哈希表是(反向键/值)
你把你的邮政编码改成这行
MyClass a = (int)enumerator.Value;
您的示例当然有效,但我在操作代码中找不到任何错误。它应该会起作用,事实上我也尝试过类似的代码,效果非常好。OP在测试中可能有一些奇怪的地方,很多这样的问题已经发布在了SO中。谢谢你的帮助和时间,我从头开始做了,现在它工作得很好。