Well, here is my problem.I've got Form1 and datagridview on it, I want to pass values of selected object from datagrid to Form2 into textBoxName and textBoxQuantity using bindingSource on Form2. Here are the pics(sorry,but I can't put them directly because of 10min points restriction) http://i58.tinypic.com/hwy6g0.jpg
http://i60.tinypic.com/20fdt14.jpg
So far, I've made class Product, and custom Collection ProductCollection with method ReadAllProducts()
class ProductsCollection : List<Products>
{
public ProductsCollection ReadAllProducts()
{
Products product = null;
ProductsCollection pCollection = new ProductsCollection();
MySqlConnection cnn = new MySqlConnection(Konekcija.cnndbpos);
MySqlCommand cmd = new MySqlCommand("SELECT *FROM products", cnn);
try
{
cnn.Open();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
product = new Products();
product.Id = Int32.Parse(dr[0].ToString());
product.Name = dr[1].ToString();
product.Quantity = Int32.Parse(dr[2].ToString());
pCollection.Add(product);
}
cnn.Close();
}
catch (Exception xcp)
{
MessageBox.Show(xcp.Message);
}
return pCollection;
}
I used bindingSource to bind collection to dataGridview from designer.
private void Form1_Load(object sender, EventArgs e)
{
ProductsCollection pc = new ProductsCollection();
bindingSource1.DataSource = pc.ReadAllProducts();
}
I want to do the exact thing on form2 using bindingSource. So far, I've done this,button edit , form1.
Products p = new Products();
Products pCurrent = (Products)dataGridView1.CurrentRow.DataBoundItem;
if (dataGridView1.CurrentCell.RowIndex > -1)
{
p.Id = pCurrent.Id;
p.Name = pCurrent.Name;
p.Quantity = pCurrent.Quantity;
}
Form2 f2 = new Form2();
f2.Show();
As DanielVorph state, you need to leverage on Current property of BindingSource object:
//This is from button edit in Form1
var prod = bindingSource1.Current as Products;
var frm2 = new Form2(prod);
frm2.Show();
The next step is to create a constructor in Form2 that takes a parameter of type Products
public class Form2: Form {
public Form2(Products product){
bindingSource2.DataSource = product;
}
}
In Form2 you have to drop a another BindingSource and set its DataSource property at designtime to Products type, then setup databinding for textBoxName and textBoxQuantity to point its Text properties to the binding source you just created for Form2. Here are a couple of picture as it is better illustrated.