![](/img/trans.png)
[英]How to show a value in combobox when i select a row of datagrid in wpf?
[英]the combobox show always the first value when i open it from another form not the value from datagrid
我有一個包含兩個組合框(cmbSection,cmbGrade)和兩個文本框(txtName,txtSectionSize)的表單,我想從combobox和txtSectionSize中獲取文本並將其放在txtName中,所以我的代碼鎖定像這樣
public partial class FRM_Item : Form
{
//public string State = "Add";
BL.CLS_Item prd = new BL.CLS_Item();
public FRM_Item()
{
InitializeComponent();
cmbSection.DataSource = prd.Get_All_Items();
cmbSection.DisplayMember = "Name_SectionType";
cmbSection.ValueMember = "ID_SectionType";
cmbGrade.DataSource = prd.Get_All_Grade();
cmbGrade.DisplayMember = "Name_Grade";
cmbGrade.ValueMember = "ID_Grade";
}
private void cmbSection_SelectedIndexChanged(object sender, EventArgs e)
{
this.txtName.Text = cmbSection.Text + txtSectionSize.Text + "-" + cmbGrade.Text;
}
private void cmbGrade_SelectedIndexChanged(object sender, EventArgs e)
{
this.txtName.Text = cmbSection.Text + txtSectionSize.Text + "-" + cmbGrade.Text;
}
private void txtSectionSize_TextChanged(object sender, EventArgs e)
{
this.txtName.Text = cmbSection.Text + txtSectionSize.Text + "-" + cmbGrade.Text;
}
當我打開表單時,我在txtName中得到System.Data.DataRowView,但是當我從組合框中選取任何文本時,我在文本框中獲得了正確的值,我通過將這段代碼移到表單加載中解決了這個問題
private void FRM_Item_Load(object sender, EventArgs e)
{
cmbSection.DataSource = prd.Get_All_Items();
cmbSection.DisplayMember = "Name_SectionType";
cmbSection.ValueMember = "ID_SectionType";
cmbGrade.DataSource = prd.Get_All_Grade();
cmbGrade.DisplayMember = "Name_Grade";
cmbGrade.ValueMember = "ID_Grade";
}
當我從另一個窗體的按鈕中打開此窗體時出現的問題,組合框始終顯示第一個值,而不是datagrid的值
private void btnEdit_Click(object sender, EventArgs e)
{
FRM_Item frm = new FRM_Item();
frm.txtName.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
frm.cmbSection.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
frm.txtSectionSize.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString();
frm.cmbGrade.Text = this.dataGridView1.CurrentRow.Cells[4].Value.ToString();
frm.ShowDialog();
}
我該如何解決這個問題
分配組合框之前,請先分配它們。 現在,它倒退了。
我建議將此代碼移到子窗體構造函數或在嘗試在父窗體中分配屬性之前可以調用的方法。
cmbSection.DataSource = prd.Get_All_Items();
cmbSection.DisplayMember = "Name_SectionType";
cmbSection.ValueMember = "ID_SectionType";
cmbGrade.DataSource = prd.Get_All_Grade();
cmbGrade.DisplayMember = "Name_Grade";
cmbGrade.ValueMember = "ID_Grade";
至於將代碼放入構造函數中的事件,如果您還沒有完成構造函數,或者沒有在設計器中擁有事件並在構造函數中明確地進行操作,則可以具有布爾屬性以不運行事件代碼填充組合框之后。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.