我已经生成了一个mysql查询,它提供了以下输出
name club countryid positionId description playersId DeleteFlag totalClubs
Sidd qegvwrwrvbwrdb 9 4 dvwrd 17 0 rvwb
goals caps positionName countryName
1212 12 Angriff Chile
查询:
select
a.*, p.positionName, c.countryname
from
soccerplayers a
left join
countries c on c.countryId = a.countryId
left join
positions p on p.positionId = a.positionId
where
a.DeleteFlag = 0
我只想要名字,俱乐部,描述,总俱乐部,目标,上限,positionName和countryName
C#代码
string cs = ConfigurationManager.AppSettings["ConnectionString"];
MySqlConnection register = new MySqlConnection(cs);
register.Open();
MySqlCommand cmd = new MySqlCommand("select a.*,p.positionName,c.countryname from soccerplayers a left join countries c on c.countryId=a.countryId left join positions p on p.positionId=a.positionId where a.DeleteFlag=0", register);
MySqlDataAdapter dataadapter = new MySqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
dataadapter.Fill(ds, "soccerplayers");
register.Close();
DataTable dt = new DataTable();
dt = ds.Tables["soccerplayers"];
foreach (DataRow dr in dt.Rows)
{
string name = dr[0].ToString();
string club = dr[1].ToString();
string country = dr[11].ToString();
string position = dr[10].ToString();
string TotalClubs = dr[7].ToString();
string description =dr[4].ToString();
string Goals = dr[8].ToString();
string caps = dr[9].ToString();
List<string> list = new List<string>();
list.Add(name);
list.Add(club);
list.Add(country);
list.Add(position);
list.Add(TotalClubs);
list.Add(Goals);
list.Add(caps);
list.Add(description);
}
GridView1.DataSource = list;
GridView1.DataBind();
答案 0 :(得分:1)
首先,如果您修改足球运动员表的定义,您的代码可能会完全废弃,因为所有这些序数都可能会发生变化。您应该考虑重写查询以便它A)不使用select *(从不使用select *);和B)只检索你需要的字段。
如果重写该查询,则可以将结果绑定到gridview,而无需迭代DataTable,分配变量,创建列表等。绑定表时,可以选择将AutoGenerateColumns设置为true(以使它更容易)或错误(如果你需要更多的布局控制)。