[英]listbox1 to listbox2 looped from listbox1 using sql query? Is it possible?
[英]C# Using value from Listbox1 for SQL Query to filter Listbox2
我有三个 SQL 表 - Team(Id,Name),Player(Id,Name)和 TeamPlayer(Id,TeamID,PlayerID)。 我的表单上还有两个 ListBox,并且希望在第一个 ListBox 上选择项目时过滤第二个 ListBox。
这主要是设置,但我遇到的问题是代码不喜欢在注释行的 LstTeams_SelectedIndexChanged 方法中传递给它的值。
private void Form1_Load(object sender, System.EventArgs e)
{
showTeams();
}
private void showTeams()
{
// Create the SQL Query, and an SqlDataAdapter using this query and sqlConnection declared earlier
string query = "select * from Team";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
// Get the 'Team' Table and Fill it
DataTable teamTable = new DataTable();
sqlDataAdapter.Fill(teamTable);
// Populate the 'Team' ListBox with the 'Team' Table
lstTeams.DataSource = teamTable.DefaultView;
lstTeams.DisplayMember = "Name";
lstTeams.ValueMember = "Id";
}
private void LstTeams_SelectedIndexChanged(object sender, System.EventArgs e)
{
string TeamID = lstTeams.GetItemText(lstTeams.SelectedValue);
MessageBox.Show("TeamID: " + TeamID);
// Create the SQL Query, and an SqlDataAdapter using this query and sqlConnection declared earlier
string query = "select * from Player p inner join TeamPlayer tp on p.Id = tp.PlayerID where tp.TeamID = @TeamID";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlCommand.Parameters.AddWithValue("@TeamID", lstTeams.SelectedValue); // this
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand); // causes the dataadapter to error
// Get the 'Team' Table and Fill it
DataTable teamTable = new DataTable();
sqlDataAdapter.Fill(teamTable);
// Populate the 'Team' ListBox with the 'Team' Table
lstPlayers.DataSource = teamTable.DefaultView;
lstPlayers.DisplayMember = "Name";
}
我的错误是:
System.ArgumentException: 'No mapping exists from object type System.Data.DataRowView to a known managed provider native type.'
我已经查找了一些解决方案,但无法获得有效的结果。
感谢您提供的任何帮助:)。
经过进一步研究并从对我的问题的评论中获得了一些指导,我在以下方面取得了成功:
DataRowView data = lstTeams.SelectedItem as DataRowView;
int TeamID = int.Parse(data["Id"].ToString());
string query = "select * from Player p inner join TeamPlayer tp on p.Id = tp.PlayerID where tp.TeamID = " + TeamID;
在 ListBox1.SelectedIndexChanged 方法内部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.