[英]Bind to Combo box based on Data Gridview selection
I have this problem; 我有这个问题;
int gender = int.Parse(row.Cells[0].Value.ToString()); int性别= int.Parse(row.Cells [0] .Value.ToString()); cmbGender.SelectedValue = gender;
cmbGender.SelectedValue =性别;
Its quite hard to help you because you did not publish all the relevant parts of your code in an organized manner. 因为您没有以有组织的方式发布代码的所有相关部分,所以很难为您提供帮助。
i see you are new here please read: How do I ask a good question . 我看到你是新来的,请阅读: 我如何问一个好问题 。
because there are missing parts in your question i will make some assumptions. 因为您的问题中缺少某些部分,所以我会做一些假设。
please try to understand the principals of my answer . 请尝试理解我回答的原理 。
Datatable
in order to retrieve data from database. Datatable
以便从数据库检索数据。 i suggest to use dictionary in order to get the gender of the ID in each Cellclick
event 我建议使用字典以获取每个
Cellclick
事件中ID的性别
please read comments inside the code: 请阅读代码中的注释:
private void Form1_Load(object sender, EventArgs e)
{
GetDataFromDataBase();
}
Dictionary<int, int> IdGenderDict;
private void GetDataFromDataBase()
{
// get data from database
DataTable dt = DAL.DataBase.GetData();
// set datagridview
dtGrdAdd.DataSource = dt;
// initilize dictionary that willl hold key value pair for ID against its gender
IdGenderDict = new Dictionary<int, int>();
// set the dictionary
for (int i = 0; i < dt.Rows.Count; i++)
{
IdGenderDict.Add(Convert.ToInt32(dt.Rows[i]["ID"].ToString()),
Convert.ToInt32(dt.Rows[i]["Gender"].ToString()));
}
}
private void dtGrdAdd_CellClick(object sender, DataGridViewCellEventArgs e)
{
// get the selected id from the datagridview
var id = Convert.ToInt32(this.dtGrdAdd.Rows[e.RowIndex].Cells["ID"].ToString());
// find the gender using the dictionary
var gender = IdGenderDict[id];
// set the combobox with the gender
if (gender == 0)
{
cmbGender.SelectedItem = "MALE";
}
else
{
cmbGender.SelectedItem = "FEMALE";
}
}
From Databse via storedProcedure: Gender.ID AS GenderID, Gender.Gender, 从Databse通过storedProcedure:Gender.ID作为GenderID,Gender.Gender,
INNER JOIN Gender ON Gender.ID = Staff.Gender 内联性别ON Gender.ID = Staff.Gender
In WinForms: 在WinForms中:
private void dtGrdAdd_CellClick(object sender, DataGridViewCellEventArgs e) 私有void dtGrdAdd_CellClick(对象发送者,DataGridViewCellEventArgs e)
{ {
//gets a collection that contains all the rows DataGridViewRow row = this.dtGrdAdd.Rows[e.RowIndex];
//获取一个包含所有行的集合
DataGridViewRow row = this.dtGrdAdd.Rows[e.RowIndex];
// row.Cells[4].Value represents the index of the Row on the DataGridView // row.Cells [4] .Value代表DataGridView上Row的索引
int gender = int.Parse(row.Cells[4].Value.ToString()); cmbGender.SelectedValue = gender;
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.