我需要添加"选择"在索引0处,不知道DataTable列的计数或名称,因为DataAccessLayer中的此方法将在稍后使用`
// ComboBox Fill Method
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cbo.DataSource = dt;
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}
答案 0 :(得分:1)
我已通过以下代码解决了这个问题。 谢谢大家...
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
DataRow drow = dt.NewRow();
for (int i = 0; i < dt.Columns.Count ; i++)
{
if (dt.Columns[i].ColumnName == cboDisplayMember)
{
drow[i] = "Select";
}
else if (dt.Columns[i].ColumnName == cboValueMember)
{
drow[i] = 0;
}
else
{
drow[i] = null;
}
}
dt.Rows.InsertAt(drow, 0);
cbo.DataSource = dt;
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}
答案 1 :(得分:0)
只需将此行放在ComboBoxFill()函数中即可。
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cbo.DataSource = dt;
DataRow newRow = dt.NewRow();
newRow[0] = "Select";
dt.Rows.InsertAt(newRow, 0);
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}
它将添加&#34;选择&#34;在位置0