C# 从数据库中填充选项
我想从数据库中的表中填写C# 从数据库中填充选项,c#,sql-server,database,choice,C#,Sql Server,Database,Choice,我想从数据库中的表中填写sList 我该怎么做 也许这会有帮助 SqlConnection cnn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "select * from [Test]"; cnn.Open(); SqlDataAdapter adp = new SqlDataAdapter(cmd); Dat
sList
我该怎么做 也许这会有帮助
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [Test]";
cnn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
Choices sList = new Choices();
1) 从属性中获取所需的表:
Choices sList = new Choices();
foreach (DataRow dr in ds.Table[0].Rows) {
sList.Name = dr["name"]; // Or whatever your property is
}
2) 创建一个方法,将每个DataRow
转换为Choices
列表中所需的类的实例(在本例中,我称之为Choice
):
您可以在文档中了解如何从DataRow
检索数据
3) 遍历行:
Choice DataRowToChoice(DataRow row)
{
return new Choice() { Property1 = row["column1"] as string }; // ... etc.
}
可以找到行
属性的文档
Choice DataRowToChoice(DataRow row)
{
return new Choice() { Property1 = row["column1"] as string }; // ... etc.
}
foreach (var row in dataTable.Rows)
{
sList.Add(DataRowToChoice(row));
}