我有一个带有买家列表的下拉菜单,我正在尝试根据下拉列表中的用户选择将sql查询结果绑定到listview。下面是代码,但列表视图根本没有显示。
protected void DropDownListSearchByBuyer_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT Team_Name FROM Team WHERE Team_ID = @Team_ID", con);
cmd.Parameters.AddWithValue("@Team_ID", DropDownListSearchByBuyer.Text);
con.Open();
var reader = cmd.ExecuteReader();
ListView1.DataSource = reader;
ListView1.DataBind();
}
Listview代码
<asp:ListView ID="ListView1" runat="server">
</asp:ListView>
答案 0 :(得分:0)
在Listview中添加ItemTemplate以显示如下所示的列。
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<span><%# Eval("Team_Name") %><span>
</ItemTemplate>
</asp:ListView>
有关详细信息,请参阅文章:https://msdn.microsoft.com/en-us/library/bb398790.aspx
答案 1 :(得分:0)
void SetListView()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT Team_Name FROM Team WHERE Team_ID = @Team_ID", con);
cmd.Parameters.AddWithValue("@Team_ID", DropDownListSearchByBuyer.Text);
con.Open();
var reader = cmd.ExecuteReader();
var readerdata = GetReaderData(reader);
reader.Close();
reader = null;
con.Close();
con = null;
ListView1.DataSource = readerdata;
ListView1.DataBind();
}
DataTable GetReaderData(IDataReader reader)
{
DataTable dtSchema = reader.GetSchemaTable();
DataTable readerData = new DataTable();
if (dtSchema == null)
{
return readerData;
}
for (int i = 0; i < dtSchema.Rows.Count; i++)
{
DataColumn dc = new DataColumn();
dc.ColumnName = dtSchema.Rows[i]["ColumnName"].ToString();
readerData.Columns.Add(dc);
}
while (reader.Read())
{
DataRow dr = readerData.NewRow();
for (int i = 0; i < readerData.Columns.Count; i++)
{
dr[readerData.Columns[i].ColumnName] = reader[readerData.Columns[i].ColumnName];
}
readerData.Rows.Add(dr);
}
return readerData;
}
阅读数据后始终
Close
读者