【发布时间】:2017-05-16 17:03:31
【问题描述】:
我已经搜索了我的问题的答案,但我找不到专门针对我的问题的解决方案,所以我不得不再发一篇文章。
当我在球队列表框中选择另一个项目时,我想更改球员列表框中的项目。
例如,如果我在球队列表框中选择了 team1,我应该在球员列表框中获取球队 1 的球员。
我的程序在 adapter.fill(playertable) 部分失败,我得到错误:
System.ArgumentException : 不存在从对象类型 System.Data.DataRowView 到已知托管提供程序本机类型的映射。
我创建了 3 个 sql 表,分别是 player、team 和 team_player,它们用作玩家和团队之间的关联表。
另外,如果我尝试通过Messagebox.Show(listboxpteams.SelectedValue.ToString()) 获取团队列表框中所选项目的值,我没有得到值,但我得到了 System.Data.DataRowView。
这是我的代码:
public partial class Form2 : Form
{
SqlConnection connection;
string connectionString;
public Form2()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["Peehootee.Properties.Settings.playersConnectionString"].ConnectionString;
}
private void Form2_Load (object sender, EventArgs e)
{
fillteams();
}
private void fillteams()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT name FROM team", connection))
{
DataTable teamtable = new DataTable();
adapter.Fill(teamtable);
listboxteams.DisplayMember = "name";
listboxteams.ValueMember = "Idteam";
listboxteams.DataSource = teamtable;
}
}
private void populateplayers()
{
String query = "Select a.firstname+ ' ' + a.surname AS Name, From player a inner JOIN team_player b on a.Idplayer = b.playerid where b.teamid = @Idteam";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue("@Idteam",listboxteams.selectedvalue);
DataTable playertable = new DataTable();
adapter.Fill(playertable);
listboxplayers.Displaymember = "Name";
listboxplayers.ValueMember = "Idplayer";
listboxplayers.DataSource = playertable;
}
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void listboxteams_SelectedIndexChanged(object sender, EventArgs e)
{
populateplayers();
}
}
}
【问题讨论】:
-
用团队填充列表框的查询没有名为 idteam 的字段是错字还是严重错误?
-
填充播放器的查询不正确(最后一个字段后的逗号)这似乎是一个错字,否则您应该在第一次使用查询时遇到语法错误异常(再次 idplayer i> 在查询文本中缺失)
-
查询有效,我测试过了。我想我在这篇文章中有一个错字,因为我没有收到语法错误。我的球员表主键是 Idplayer,球队表主键是 Idteam,关联表外键是 playerid 和 teamid。
标签: c# database winforms listbox