[英]Fill ComboBox DataSource from DataTable
在返回字符串的字段上使用以下代碼時,它可以正常工作,但是當該字段的類型為long或Double時,會出現錯誤:
分別。
string f = cb.Name.Substring(2, cb.Name.Length - 2);
cb.DataSource = SQLite.GetValues(f).AsEnumerable()
.Select<System.Data.DataRow, String>(x => x.Field<string>(f))
.ToArray();
在上面的SQLite.GetValues中返回一個數據表。 我試圖用作組合框的數據源。
我可以對此Linq語句進行一些小的更改以使其起作用嗎?
當我更改代碼行.Select<System.Data.DataRow, String>(x => x.Field<string>(f))
到.Select<System.Data.DataRow, Int64>(x => x.Field<Int64>(f))
或.Select<System.Data.DataRow, Double>(x => x.Field<Double>(f))
,然后適用於那些字段,但不適用於其他字段。
缺少使用if語句先檢查該字段然后運行適當的代碼行的方法,還有其他解決方法嗎?
GetValues
方法還用於填充具有所有列的DataGridView的DataSource,這就是為什么我不只是從GetValues
返回列表或數組的原因
還考慮了是否只是在返回的DataTable的DataRows上循環以填充ComboBox也許這是最好的?
例如:
string f = cb.Name.Substring(2, cb.Name.Length - 2);
DataTable dt = new DataTable();
dt = SQLite.GetValues(f,false);
foreach (DataRow dr in dt.Rows)
{
cb.Items.Add(dr[f]);
}
要將字段轉換為字符串,請使用.ToString()方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.