我已经搜索了我的问题的答案,但我找不到专门针对我的问题的解决方案,所以我不得不另外发帖。
我想在团队列表框中选择其他项目时更改播放器列表框中的项目。
例如,如果我在团队列表框中选择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();
}
}
}
答案 0 :(得分:0)
您的问题是由用于填充列表框的查询文本中缺少字段 idplayer 引起的。如果没有此字段,将ValueMember属性设置为您尚未从数据库中检索的字段是没有意义的。当您尝试读取SelectedValue时,绑定引擎不知道返回到您的代码的内容,因此它返回用于将DataTable绑定到ListBox的类的名称(A DataRowView)
顺便说一下,如果你交换属性设置的顺序,你会得到一个ArgumentException,说明究竟是什么问题
试试这个......
listboxplayers.DataSource = playertable;
listboxplayers.Displaymember = "Name";
listboxplayers.ValueMember = "Idplayer";
设置ValueMember属性时发生ArgumentException。
在播放器和团队查询中修复您的查询,以包含 idplayer 和 idteam
首先在这里......
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT idteam, name FROM team", connection))
还有......
String query = @"Select a.idplayer,
a.firstname+ ' ' + a.surname AS Name
From player a inner JOIN team_player b
on a.Idplayer = b.playerid
where b.teamid = @Idteam";