我正在尝试将记录(性别)从我的数据库加载到我的窗口表单,以便在表单加载时自动加载,我遇到了挑战,因为它只从数据库中获取ID,而不是性别名称,我该怎么做?下面是我编写它的代码片段
private void Form1_Load(object sender, EventArgs e)
{
Load_Gender();
}
public void Load_Gender()
{
try
{
string connectionString = @"Data Source=localhost;" +
"Initial Catalog=DemoDb;Integrated Security=true; User Instance=False";
SqlConnection connection = new lConnection(connectionString);
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT * FROM Gender";
SqlDataAdapter sl = new SqlDataAdapter(command);
DataSet ds = new DataSet();
sl.Fill(ds, "Table");
DataTable dt = ds.Tables["Table"];
foreach (DataRow row in dt.Rows)
{
string id = row["Id"].ToString();
string genderName = row["GenderName"].ToString();
}
// Loading RECORDS to comboBox
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBoxGender.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
}
catch()
{
}
}
发布于 2017-04-12 18:47:17
您的foreach循环本质上什么也不做,除非您将其放入调试以检查每一行包含的内容,尽管您可以只检查内存中的数据表定义。
comboBoxGender.Items.Add(ds.Tables[0].Rows[i][0].ToString());
这段代码只获取Id,因此Rowsi,0是第一列。
Rowsi是性别名称。
https://stackoverflow.com/questions/43377145
复制相似问题