大家好:
comboBox[i].Items.Add(ds.Tables[0].Rows[j][i].ToString()); //想請問column中的rows要怎麼不取重複值?
好像可以用但不知道要怎麼加,謝謝!
DataView dv = ds.Tables[0].DefaultView;
DataTable dtDistinct = new DataTable();
dtDistinct = dv.ToTable(true, ds.Tables[0].Columns[i].ColumnName);
var txtCommand = "SELECT * FROM [" + tablename + "]";
OleDbDataAdapter da = new OleDbDataAdapter(txtCommand, conn);
DataSet ds = new DataSet();
da.Fill(ds);
int n = 2; //myDataTable.Columns.Count;
ComboBox[] comboBox = new ComboBox[n];
Label[] label = new Label[n];
for (int i = 0; i < n; i++)
{
comboBox[i] = new ComboBox();
comboBox[i].Size = new Size(80, 26);
comboBox[i].Name = "n" + i;
comboBox[i].Location = new Point(85, 9);
label[i] = new Label();
label[i].Size = new Size(50, 26);
label[i].Name = "n" + i;
label[i].Text = ds.Tables[0].Columns[i].ColumnName + ":";
label[i].Location = new Point(1, 90);
label[i].TextAlign = ContentAlignment.MiddleCenter;
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
comboBox[i].Items.Add(ds.Tables[0].Rows[j][i].ToString()); //想請問column中的rows要怎麼不取重複值?
}
fm4.tableLayoutPanel1.Controls.Add(comboBox[i], i + 2, 0);
fm4.tableLayoutPanel1.Controls.Add(label[i], i + 2, 0);
}
這樣好像就可以了..@@
var val = ds.Tables[0].Rows[j][i].ToString();
if (!comboBox[i].Items.Contains(val))
{
comboBox[i].Items.Add(ds.Tables[0].Rows[j][i].ToString());
}
}
看的好辛苦,幫你簡化一下,用lambda GroupBy就可以取唯一值,唯讀而已不用for(),改用foreach比較明瞭一點
SqlConnection sconn = new SqlConnection("Data Source=192.168.1.100;Initial Catalog=MenuData;Persist Security Info=True;User ID=sa;Password=12345");
SqlCommand scmd = new SqlCommand("SELECT * FROM Menu", sconn);
SqlDataAdapter sda = new SqlDataAdapter(scmd);
DataTable dt = new DataTable();
sda.Fill(dt);
var menuitem = dt.AsEnumerable()
.GroupBy(g => g.Field<string>("menuname"))
.Select(s => s.Key);
foreach (var r in menuitem)
{
comboBox1.Items.Add(r);
}
謝謝j大,像lambda GroupBy的使用,要怎麼查..書很少寫這類
我只能查overstackflow找相關的例子,您寫得很精簡!
只有一個表不用到DataSet ...
Linq , Lambda 是個很深的海洋....
https://ithelp.ithome.com.tw/articles/10100451