code does not display anything in datagridview
why?
class classman
{
public int id;
public string name;
}
private void Form2_Load(object sender, EventArgs e)
{
testtelContext db = new testtelContext();
List<classman> qry = (from p in db.firstlasts
join i in db.firstnames
on p.Idfname equals i.Idfname
select new classman
{
id = p.idfl,
name = i.fname
}).ToList();
BindingSource bs=new BindingSource();
bs.DataSource = qry;
dataGridView1.DataSource = bs;
}
There is value in bindingsource but it does not display dataGridView5 show picture http://irphoto.ir/uploads/13658793021.jpg
Probably need this:
dataGridView1.DataBind();
Right after you set the data source.
Related
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.
As title suggests, I want to show the values of comboBox2 when values are in comboBox1 get change.
For.Eg: We have mealtypes in comboBox1 (burger,cold drink, biryani) and we want to show Values in comboBox2 like when someone selects Burger from comboBox1 then there should be Chicken Burger,Beef Burger, Zinger Burger in ComboBox 2 which we have mentioned in database in Meals table and we have also made a table of Meal Types in database (Meal Types will be in comboBox1 and Meals will be in comboBox2 in Visual Studio Form).
public partial class ordermeal: Form {
public ordermeal() {
InitializeComponent();
}
Meal_Delivery_Management_System md = new Meal_Delivery_Management_System();
private void ordermeal_Load(object sender, EventArgs e) {
comboBox1.DataSource = md.GetALLMealTypes();
comboBox1.DisplayMember = "typename";
comboBox1.ValueMember = "mealtypeid";
comboBox2.DataSource = md.GetMeals();
comboBox2.DisplayMember = "Mealname";
comboBox2.ValueMember = "unitprice";
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) {
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e) {
}
}
make two methods for your Combobox and call your mealtype combobox in constroctor
here is sample
public ordermeal()
{
InitializeComponent();
yourMealtypeCombobox();
}
public void yourMealtypeCombobox()
{
DataTable dt = md.GetALLMealTypes(); //
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "typename";
comboBox1.ValueMember = "mealtypeid";
}
public void yourMealCombo(int mealtypeid)
{
DataTable dt = md.GetMeals(mealtypeid); // Get your corresponding meal by mealtypeid of Selected mealtype by users
/* i am assuming your GetMeals() method is able to except input parameter and filter records from input parameter */
comboBox2.DataSource = dt;
comboBox2.DisplayMember = "Mealname";
comboBox2.ValueMember = "unitprice";
}
and call combobox selection changedcommited event of both combobox1
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
// here Get the Selected Type of of meal
int mealTypeId = Convert.ToInt32(comboBox1.SelectedValue);// here i am not checking null but you should do it
// finaly call mealcombo from here
yourMealCombo(mealTypeId);
}
I have 2 listboxes in a window form, one on left and one on right. The
1st listbox have some items while the 2nd listbox is empty. Also there
are 2 buttons between the 2 listboxes which used to move item from/to
the 1st and 2nd listbox
My problem here is that after I bind the data to the 1st listbox (from
a database, using DisplayMember and ValueMember) , and I try to move 1
of the item from this 1st listbox to the 2nd listbox and I want that
the selected item is also removed from the 1st listbox by:
private void btnMoveRight_Click(object sender, EventArgs e)
{
ADD();
}
private void ADD()
{
int c = listJobBox.Items.Count - 1;
` for(int i= c; i>=0; i--)
{
if(listJobBox.GetSelected(i))
{
lstAssignedJobs.Items.Add(listJobBox.Items[i]);
listJobBox.Items.Remove(listJobBox.SelectedItem); ---error line
But the selected item is not removed from the 1st listbox.
it displays error message "Items collection cannot be modified
when the DataSource property is set."
can any one give me the solution to my problem.
Add a boolean column to your DataTable object, something like IsSelected.
Then instead of binding your listbox1 directly to the table, bind it to a BindingSource. Add 2 bindingsources to your form using the designer. And place this code in your code behind file.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.InitializeDataObjects();
}
private void InitializeDataObjects()
{
this.InitData();
this.InitBindingSources();
}
private void InitData()
{
ds = new DataSet();
var dt = new DataTable("Table1");
dt.Columns.Add("Name", typeof(string));
ds.Tables.Add(dt);
}
private void InitBindingSources()
{
bindingSource1 = new BindingSource();
bindingSource2 = new BindingSource();
bindingSource1.DataSource = ds;
bindingSource1.DataMember = "Table1";
bindingSource2.DataSource = ds;
bindingSource2.DataMember = "Table1";
listBox1.DataSource = bindingSource1;
listBox1.DisplayMember = "Name";
listBox2.DataSource = bindingSource2;
listBox2.DisplayMember = "Name";
}
}
Then when you load your data, do the following:
private void btnLoadAndBind_Click(object sender, EventArgs e)
{
this.FetchData(this.ds.Tables["Table1"]);
this.AddSelectedColumn(this.ds.Tables["Table1"]);
this.bindingSource1.Filter = "IsSelected = false";
this.bindingSource2.Filter = "IsSelected = true";
}
private void FetchData(DataTable dataTable)
{
string CS = "your connectionstring";
using (SqlConnection con = new SqlConnection(CS))
{
try
{
SqlDataAdapter da = new SqlDataAdapter();
con.Open();
var sqlcmd = new SqlCommand("SELECT Name FROM sometable", con);
sqlcmd.CommandType = CommandType.Text;
da.SelectCommand = sqlcmd;
da.Fill(dataTable);
}
catch (Exception ex)
{
MessageBox.Show("exception raised");
throw ex;
}
}
}
private void AddSelectedColumn(DataTable suppliersDataTable)
{
var dc = new DataColumn("IsSelected", typeof(bool));
suppliersDataTable.Columns.Add(dc);
foreach (DataRow dr in suppliersDataTable.Rows)
{
dr["IsSelected"] = false;
}
}
Now your listboxes are both connected to the same datatable and filtered based on the IsSelected property / column. Just set this column to true or false and it will flip from box to box. Your eventhandler of a button could look like this:
public void button_Click(object sender, EventArgs e)
{
if (this.bindingSource1.Current!= null)
{
var dr = ((DataRowView)this.bindingSource1.Current).Row;
dr["IsSelected"] = true;
}
}
This works!
Things will be become much simpeler if you use a typed dataset. Most of the bindings then can be done in the designer and your code behind will shrink to 20 lines of code....
Lets say listbox1 is bound to datatable1 (it could be any other collection type) and listbox2 is bound to datatable2. When you click on move button, remove the selected item from the collection i.e datatable1 and add that item to other collection i.e. datatable2 and re-bind the listbox1 and lisbox2.
Here is a rough working example:
public partial class Form1 : Form
{
private DataTable _dataSource1;
private DataTable _dataSource2;
public Form1()
{
InitializeComponent();
_dataSource1 = GetData1();
_dataSource2 = GetData2();
Initialize();
}
private void btnMove_Click(object sender, EventArgs e)
{
MoveItem();
}
void Initialize()
{
listBox1.DataSource = _dataSource1;
listBox1.DisplayMember = "Fruits";
listBox1.ValueMember = "Fruits";
listBox2.DataSource = _dataSource2;
listBox2.DisplayMember = "Fruits";
listBox2.ValueMember = "Fruits";
}
DataTable GetData1()
{
var dt = new DataTable();
dt.Columns.Add("Fruits");
dt.Rows.Add(new object[] {"Apple"});
dt.Rows.Add(new object[] { "Orange" });
dt.Rows.Add(new object[] { "Grapes" });
return dt;
}
DataTable GetData2()
{
var dt = new DataTable();
dt.Columns.Add("Fruits");
return dt;
}
void MoveItem()
{
var index = listBox1.SelectedIndex;
var dataRowToRemove = _dataSource1.Rows[index];
var listItem = dataRowToRemove[0] as string;
_dataSource1.Rows.Remove(dataRowToRemove);
var dataRowToAdd = _dataSource2.NewRow();
dataRowToAdd[0] = listItem;
_dataSource2.Rows.Add(dataRowToAdd);
Initialize();
}
}
I am working in Winforms and now got stuck; I have created a custom usercontrol for textbox as shown in the code below:
public partial class TextBox : UserControl
{
public TextBox()
{
InitializeComponent();
txtTEXT.Text = "";
}
[DefaultValue("Text")]
public string Caption
{
get { return lblCAPTION.Text; }
set { lblCAPTION.Text = value;}
}
[Browsable(true)]
public new string Text
{
get { return txtTEXT.Text; }
set { txtTEXT.Text = value; }
}
[Browsable(true),DefaultValue(100)]
public int Caption_Width
{
get { return lblCAPTION.Width; }
set { lblCAPTION.Width = value; }
}
private void txtTEXT_TextChanged(object sender, EventArgs e)
{
if (this.txtTEXT.Text.StartsWith("textBox"))
this.txtTEXT.Text = "";
}
public new BorderStyle BorderStyle
{
get { return txtTEXT.BorderStyle; }
set { txtTEXT.BorderStyle = value; }
}
public bool PasswordChar
{
get { return txtTEXT.UseSystemPasswordChar; }
set {txtTEXT.UseSystemPasswordChar = value ;}
}
public bool m_Mandatory = false;
public bool Mandatory
{
get { return m_Mandatory; }
set
{
m_Mandatory= value;
lblAMENDATORY.Visible = m_Mandatory;
}
}
private void TextBox_Resize(object sender, EventArgs e)
{
this.Height = txtTEXT.Height;
}
}
Then in another form, I have binded this textbox as in the code below:
BindingSource bs = new BindingSource();
BindingSource bsDet = new BindingSource();
DataSet data;
SqlDataAdapter masterDataAdapter;
SqlDataAdapter detailsDataAdapter;
SqlConnection connection = new SqlConnection(connectionString);
// Create a DataSet.
data = new DataSet();
// Add data from the Customers table to the DataSet.
masterDataAdapter = new SqlDataAdapter("select * from RFID_MAS", connection);
masterDataAdapter.Fill(data, "RFID_MAS");
// Add data from the Orders table to the DataSet.
detailsDataAdapter = new SqlDataAdapter("select * from RFID_DET", connection);
detailsDataAdapter.Fill(data, "RFID_DET");
// Establish a relationship between the two tables.
DataRelation relation = new DataRelation("MyRelation", data.Tables["RFID_MAS"].Columns["SEQ_NO"],data.Tables["RFID_DET"].Columns["MAS_SEQ"]);
data.Relations.Add(relation);
// Bind the master data connector to the Customers table.
bs.DataSource = data;
bs.DataMember = "RFID_MAS";
// Bind the details data connector to the master data connector,
// using the DataRelation name to filter the information in the
// details table based on the current row in the master table.
bsDet.DataSource = bs;
bsDet.DataMember = "MyRelation";
// textBox1 is default Windows TextBox
textBox1.DataBindings.Add(new Binding("Text", this.bs, "RFID_NO", true, DataSourceUpdateMode.OnValidation));
// textBox2 is my ouwn usercontrol textbox
textBox2.DataBindings.Add(new Binding("Text", this.bs, "SEQ_NO",true, DataSourceUpdateMode.OnValidation));
dataGridView2.DataSource = bsDet;
dataGridView1.AutoResizeColumns();
dataGridView2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
bindingNavigator1.BindingSource = bs;
//bs.DataSource = dset.Tables[0];
//dataGridView1.DataSource = bs;
Then I am saving my textbox data as:
this.Validate();
this.bs.EndEdit();
SqlCommandBuilder cm = new SqlCommandBuilder(masterDataAdapter);
this.masterDataAdapter.Update(data.Tables[0]);
Now my problem here is that when I add a new record,
the data from TextBox1 (ie windows default textbox) get updated in the BindingSource,
but data from TextBox2 (ie my own usercontrol textbox) does not get updated in the Bindingsource.
Please Help me if I am missing out something.
Very thanks to you.
I have a function
public DataSet Select(string sql)
{
//Get data source from database to DataSet
}
in class DataDriverExample
and in form_load, I bind to the datagridview.
public BindingSource bs = new BindingSource()
public void form_load()
{
DataSource ds = DataDriverExample.Select("Select * from XYZ");
bs.DataSource = ds;
dataGridView.DataSoure = bs;
dataGridView.DataMember = "TableResult";
txtAbc.Bindings.Add("text",bs,"TableResult.Col1");
}
it worked,
but I have Button Add (which adds a new record to the database)
public void btnAdd_click()
{
DataDriverExample.Insert("Insert into XYZ values (\"Test\",\"Hello\",\"Bla\")");
DataSource ds = DataDriverExample.Select("Select * from XYZ");
bs.DataSource = ds;
bs.ResetBinding(true);
}
In my database it now has new record, but I get the error Cannot bind to the property or column on the DataSource
Sorry for my english not good.
Anyone can help me.
Tks
To Clean up your code, create another method for your binding something like:
private void LoadData()
{
bs.ResetBinding(true);
txtAbc.DataBindings.Clear()
DataSource ds = DataDriverExample.Select("Select * from XYZ");
bs.DataSource = ds;
dataGridView.DataSoure = bs;
dataGridView.DataMember = "TableResult";
txtAbc.Bindings.Add("text",bs,"TableResult.Col1");
}
Then just call LoadData(); on your formload and add method
public BindingSource bs = new BindingSource()
public void form_load()
{
LoadData();
}
Add:
public void btnAdd_click()
{
DataDriverExample.Insert("Insert into XYZ values (\"Test\",\"Hello\",\"Bla\")");
LoadData();
}
Hope this helps
Regards