我目前正在开发一个C#Windows窗体应用程序。
现在我正在尝试使用SQL命令从数据库中检索信息,以填写我需要在我的应用程序中拥有的信息。
示例查询将是“select * from Location”
在Location表中会有像locationId,LocationName,districId等变量。 我使用了以下代码
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connectionstring");
SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);
DataTable dt = new DataTable();
ada.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
ListViewItem listitem =new ListViewItem(dr["pk_Location_ID"].ToString());
listitem.SubItems.Add(dr["var_Location_Name"].ToString());
listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());
listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());
listView1.Items.Add(listitem);
}
输出结果为:
但它应该是这样的:
答案 0 :(得分:4)
你必须改变一些代码
private void button1_Click(object sender, EventArgs e)
{
listView1.View = View.Details;
SqlConnection con = new SqlConnection("connectionstring");
SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);
DataTable dt = new DataTable();
ada.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
ListViewItem listitem = new ListViewItem(dr["pk_Location_ID"].ToString());
listitem.SubItems.Add(dr["var_Location_Name"].ToString());
listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());
listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());
listView1.Items.Add(listitem);
}
答案 1 :(得分:1)
添加了以下代码
listView1.View = View.Details;
并且有效。
答案 2 :(得分:0)
private void FormView_Load(object sender, EventArgs e)
{
sample = new DataTable(); //Sample Data
sample.Columns.Add("id", typeof(string));
sample.Columns.Add("name", typeof(string));
sample.Rows.Add("1", "apple");
sample.Rows.Add("2", "acer");
sample.Rows.Add("3", "alpha");
sample.Rows.Add("4", "beat");
sample.Rows.Add("5", "ball");
sample.Rows.Add("6", "cat");
sample.Rows.Add("7", "catch");
sample.Rows.Add("10", "zebra");
listViewEx1.View = View.Details;
listViewEx1.Columns.Add("id");
listViewEx1.Columns.Add("name");
}
listViewEx1.Items.Clear();
listViewEx1.FullRowSelect = true;
foreach (DataRow row in sample.Rows)
{
ListViewItem item = new ListViewItem(row["id"].ToString());
item.SubItems.Add(row["name"].ToString());
listViewEx1.Items.Add(item); //Add this row to the ListView
}