I know it may be a duplicate question but previous question did not solve my problem.
I have Form1
and Form2
. In Form1
there is a dataGridView
with a field called category
.
In form2
I have set a combobox
. I send data from field category
of dataGridView
in form1
to this combobox
in Form2
.
I have made the identifier
of this combobox
public. There is an update button
in Form1
.
I want when I select a row and click on update button
, Form2
opens and the combobox
that is there shows the value of field category
of dataGridView
of Form1.
This is the code:
Form2 fr2 = new Form2();
fr2.cmbCategory.Text = dgvProduct.SelectedRows[0].Cells[1].Value.ToString();
fr2.Show();
Then in Form2
I have set the DataSource
of cmbCategory
to tblCategory
, and set it's Display member
to field code
.
I want cmbCategory
to show all items of field code
in tblCategory
and at the same time, one of those items be selected. And so the selected item should be the one that I pass to it from Form1
.
I wonder how can it be done? I'm new in coding and I really appreciate if you answer in a simple way. I have used visual c# to do all this.
You can do like this
Updated: Use Text instead of SelectedItem
In your Form1 cs file:
private void UpdateButton_Click_1(object sender, EventArgs e)
{
int category = 0;
Int32.TryParse(dgvProduct.SelectedRows[0].Cells[1].Value.ToString(), out category);
Form2 fr2 = new Form2(category); // You are calling parameterized constructor for Form2
fr2.Show();
}
Now in your Form2 cs file:
public partial class Form2 : Form
{
public int Category { get; set; } // Property for selected category (You need this only if you need the category outside Form2 constructor)
public Form2() // Default constructor
{
InitializeComponent();
}
public Form2(int category) // Contructor with string parameter
{
Category = category;
InitializeComponent();
cmbCategory.Text = Category.ToString(); **// Use Text property instead of SelectedItem.**
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.