private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
if (e.TabPage.Name == tabPage2.Name)
{
table = Items.Get();
comboBox1.DataSource = table;
comboBox1.DisplayMember = "Item_ID";
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
temp = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
}
I am trying to populate the comboBox1 as the tabpage open and then populate the comboBox2 based on the selectedText of comboBox1.
comboBox_SelectedIndexChange runs 2 times when tab changes but returns null every times.
Note: I have already appended event handler as the form initializes like,
public Form1()
{
InitializeComponent();
tabControl1.Selected += new TabControlEventHandler(tabControl1_Selected);
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
table = new DataTable();
s = new Stock();
}
First there is a bug in
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
temp = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
}
code. You override value for datasource in line
temp = Color.Get(text);
I think it should be like:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
selectedColor = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
comboBox2.SelectedItem = selectedColor;
}
I don't know contents of DataTable so instead of comboBox2.SelectedItem you may need to set SelectedItem, SelectedText or SelectedValue properties of comboBox2.
Suspicious line here:
string text = comboBox1.SelectedItem.ToString();
You will get text variable filled with "YourNamespace.DataTable". If your function Color.Get(text) is expecting Item_ID of selected item as parameter, then you should change that line of code above to:
string text = ((DataTable)comboBox1.SelectedItem).Item_ID;
I assumed that DataTable is an object that have Item_ID property.
private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
if (e.TabPage.Name == tabPage2.Name)
{
table = Items.Get();
if (table.Rows.Count > 0)
{
//Update comboBox1 using table
comboBox1.DataSource = table;
comboBox1.DisplayMember = "Item_ID";
//Using 1st row and 1st coloumn in function argument to get colors
//Color.Get(string itemID) returns dataTable, which I used for comboBox2 DataSource
comboBox2.DataSource = Color.Get(table.Rows[0].ItemArray[0].ToString());
comboBox2.ValueMember = "Color_ID";
comboBox2.DisplayMember = "Color_Name";
}
}
}
Related
I am new in c# and I have a question.
I want to select a value from a combobox and it should show in a label it's age.
What I do is this:
public void FillCombo()
{
SqlDataAdapter adap = new SqlDataAdapter("Select * from customers",con);
DataTable dt = new DataTable();
adap.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "id";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from customers where name=#name ", con);
cmd1.Parameters.AddWithValue("#name",comboBox1.SelectedItem));
int i= cmd1.ExecuteNonQuery();
if (i > 0)
{
SqlDataReader sqlrdr = cmd1.ExecuteReader();
while (sqlrdr.Read())
{
String age= sqlrdr["age"].ToString();
label1.Text = age;
}
}
else{
MessageBox.Show("no value");
}
con.Close();
}
It shows no value message , even if i have values in database. What can I do?
When you set the DataSource to a DataTable then every item in the combobox is a DataRowView. So you already have the info about the age of the current customer in the combobox. No need to make another call to the database.
You just need to use the SelectedItem property to retrieve the info about the age field or any other field present in the DataSource
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView rv = l.SelectedItem as DataRowView;
// For safety, always check for null.
// It is possible that SelectedIndexChanged
// will be called even when there is no selection in the combobox
if(rv != null)
{
label1.Text = rv["age"].ToString();
....
}
}
Try this to obtain index,value and selected name:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
int selectedValue = (int)cmb.SelectedValue;
ComboboxItem selectedName = (ComboboxItem)cmb.SelectedItem;
}
We want to attach a combo box into a cell of data grid view. Now it works with mouse click. but for faster moving of form we need it to work using keyboard.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void CreateGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("EmpName", typeof(string));//0
dt.Columns.Add("EmpID", typeof(int));//1
dt.Columns.Add("PhoneNo", typeof(string));//2
dt.Columns.Add("Address", typeof(string));//3
dt.Columns.Add("Email", typeof(string));//4
dataGridView1.DataSource = dt;
dataGridView1.Controls.Add(comboBox1); // Add System.Windows.Form.ComboBox in Datagridview
}
private void Form1_Load(object sender, EventArgs e)
{
CreateGrid();
fillRecords(1);
}
string SQL;
void fillRecords(int QueryNo)
{
SqlConnection con = new SqlConnection(#"Data Source=APPLE-PC\RNS;Initial Catalog=DemoDatabase;User ID=sa;Password=rns11");
con.Open();
if (QueryNo==1)
{
SQL = "Select EmpName,EmpID from EmployeeMaster";
}
else if (QueryNo==2)
{
SQL = "Select PhoneNo,Address from EmployeeMaster where EmpID=" + comboBox1.SelectedValue.ToString();
}
SqlDataAdapter da = new SqlDataAdapter(SQL, con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if (QueryNo == 1)
{
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "EmpName";
comboBox1.ValueMember = "EmpID";
}
else if (QueryNo == 2)
{
dataGridView1.CurrentRow.Cells[1].Value = comboBox1.SelectedValue.ToString();
dataGridView1.CurrentRow.Cells[0].Value = comboBox1.Text;
DataRow dr=dt.Rows[0];
dataGridView1.CurrentRow.Cells[2].Value = dr["PhoneNo"];
dataGridView1.CurrentRow.Cells[3].Value = dr["Address"];
}
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
//Visible Location on Current Cell
if (dataGridView1.CurrentCell.ColumnIndex==0)
{
comboBox1.Visible = true;
comboBox1.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Size = dataGridView1.CurrentCell.Size;
}
}
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
comboBox1.Visible = false;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue.ToString()!="System.Data.DataRowView")
{
fillRecords(2);
}
}
}
this solution is given by Sinisa Hajnal.
It should work using keyboard, but usually need to press F2 first to enter edit mode. I can solve this by handling CellEnter event and opening edit mode for combobox and setting focus to it inside.
`
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex==0)
{
comboBox1.Visible = true;
comboBox1.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Size = dataGridView1.CurrentCell.Size;
comboBox1_SelectedIndexChanged(null, null);
comboBox1.Focus();//focus on Combobox
}
}
`
I am developing an application in which i have four comboBoxes i-e (comboBox1 for class, comboBox2 for group, comboBox3 for section and combBox4 for months) and a listBox. i have fetched data from database to all of these comboBoxes in "OnLoad Function".Now i want to show student names in listBox according to the comboBoxes. i-e when i select "class 7th" from class (comboBox1). It should display those students who are in selected class (class 7th), selected group (selected in comboBox2) and selected section (selected in comboBox3). Here is my code but it gives me SQL syntax exception and indexOutOfRange exception. The database attached is in mysql. "dbOperation" is the object of the class "myDatabse" in which I have connected the database and implemented all queries.
public partial class FeeVoucherPrint : Form
{
myDatabase dbOperation = new myDatabase();
DataTable table = new DataTable();
public FeeVoucherPrint()
{
InitializeComponent();
this.MaximizeBox = false;
this.MinimizeBox = false;
}
private void FeeVoucherPrint_Load(object sender, EventArgs e)
{
table = dbOperation.select("* from class");
comboBox1.DataSource = table;
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "id";
table = dbOperation.select("* from `group`");
comboBox2.DataSource = table;
comboBox2.DisplayMember = "name";
comboBox2.ValueMember = "id";
table = dbOperation.select("* from section");
comboBox3.DataSource = table;
comboBox3.DisplayMember = "name";
comboBox3.ValueMember = "id";
table = dbOperation.select("* from months");
comboBox4.DataSource = table;
comboBox4.DisplayMember = "month";
comboBox4.ValueMember = "id";
}
private void fill()
{
try
{
table = dbOperation.select("studentid from studentinclass where classid = " + comboBox1.SelectedValue + " and groupid = " + comboBox2.SelectedValue);
table = dbOperation.select("* from student where studid = " + table.Rows[0]["studentid"]);
listBox1.DataSource = table;
listBox1.DisplayMember = "name";
listBox1.ValueMember = "studid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
fill();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
fill();
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
fill()
}
}
Looks like you are using DataTable.Select method (dbOperation.select in this case) in a wrong way.
Gets an array of all DataRow objects that match the filter criteria.
That's why your studentid from studentinclass where part in first .Select and * from student where part in second .Select are unnecessarry. They are not filters.
Read remarks part of DataColumn.Expression property documentation.
I have a GeidView in my form and I have a button which add new records to the GridView by adding a row to a Datatable and then make this DataTable as the GridContol's Data Source.
The problem is when I add a new record it display in the GridView but when I add another rocord it doesn't display in the GridView, The GridView always contains the first row I added to the DataTable !
So please could you help me to solve this problem ?
This is the source code :
private DataTable recompensesTable;
private void AjoutLivre_Load(object sender, EventArgs e)
{
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
private DataTable MakeRecomponsesTable()
{
DataTable recmpensesTable = new DataTable("Recompenses");
var anneeColumn = new DataColumn();
anneeColumn.DataType = Type.GetType("System.Int32");
anneeColumn.ColumnName = "Année";
recmpensesTable.Columns.Add(anneeColumn);
var prixLiteraireColumn = new DataColumn();
prixLiteraireColumn.DataType = Type.GetType("System.String");
prixLiteraireColumn.ColumnName = "Prix Litéraire";
recmpensesTable.Columns.Add(prixLiteraireColumn);
return recmpensesTable;
}
private void nouveauRecompense_Click(object sender, EventArgs e)
{
DataRow row = recompensesTable.NewRow();
row[0] = ajoutRecompense.KeyWordAnnee;
row[1] = ajoutRecompense.KeyWordPrixLiteraire;
recompensesTable.Rows.Add(row);
recompenseGridControl.DataSource = recompensesTable;
}
In your Page_Load you have recompensesTable = MakeRecomponsesTable();. That overwrites the changes and recreate the datatable values
On page postback, variables are restored to their default values and they need to be recreated. You can use Session to maintain your values
private void AjoutLivre_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataTable recompensesTable = MakeRecomponsesTable();
Session["recompensesTable"] = recompensesTable; //Save it to session the first time
recompenseGridControl.DataSource = recompensesTable;
}
}
and retrieve the session preserved value
private void nouveauRecompense_Click(object sender, EventArgs e)
{
DataTable recompensesTable = (DataTable) Session["recompensesTable"]; //retrieve it from session
DataRow row = recompensesTable.NewRow();
row[0] = ajoutRecompense.KeyWordAnnee;
row[1] = ajoutRecompense.KeyWordPrixLiteraire;
recompensesTable.Rows.Add(row);
Session["recompensesTable"] = recompensesTable; //save it back to session
recompenseGridControl.DataSource = recompensesTable;
}
change your
private void AjoutLivre_Load(object sender, EventArgs e)
{
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
To
private void AjoutLivre_Load(object sender, EventArgs e)
{
if(!IsPostback)
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
You also must save the datatable to session
the recmpensesTable is always a new DateTable, you should save it to session for next use.
Using Linq to sql through bindingsource control in WinForms, I could not get this to work:
private void textBox1_TextChanged(object sender, EventArgs e)
{
productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'", textBox1.Text);
MessageBox.Show("Changed");
}
NorthwindDataContext dc;
private void FrmFilter_Load(object sender, EventArgs e)
{
// create new data context
dc = new NorthwindDataContext();
// set the binding source data source to the full order table
var qry = (from p in dc.Products select p).ToList();
this.productBindingSource.DataSource = dc.GetTable<Product>();
}
When I type some letter in the textbox nothing happens in the datagridview.
Thanks for advices ...
Try changing your code to look like this:
NorthwindDataContext dc;
private void FrmFilter_Load(object sender, EventArgs e)
{
dc = new NorthwindDataContext();
this.productBindingSource.DataSource = dc.GetTable<Product>();
productDataGridView.DataSource = productBindingSource;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'",
textBox1.Text);
}
Make sure your TextChanged event is wired up and actually running. Also, I took qry out of the example since you weren't using it anywhere in the posted code.
older edits:
You shouldn't have to reset the DataSource on the grid.
Try changing it to this:
private void textBox1_TextChanged(object sender, EventArgs e) {
if (textBox1.Text == string.Empty) {
productBindingSource.RemoveFilter();
} else {
productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'", _
textBox1.Text);
}
}
I would avoid worrying about replacing those special characters at the moment. Get the filter working first.
Here is a working example with just a DataGridView and a TextBox on a form:
private DataTable dt = new DataTable("Test");
private BindingSource bs;
public Form1() {
InitializeComponent();
dt.Columns.Add("ProductName", typeof(string));
DataRow dr1 = dt.NewRow();
dr1["ProductName"] = "One A";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["ProductName"] = "One B";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3["ProductName"] = "Two A";
dt.Rows.Add(dr3);
DataRow dr4 = dt.NewRow();
dr4["ProductName"] = "Two B";
dt.Rows.Add(dr4);
bs = new BindingSource(dt, null);
dataGridView1.DataSource = bs;
}
private void textBox1_TextChanged(object sender, EventArgs e) {
if (textBox1.Text == string.Empty) {
bs.RemoveFilter();
} else {
bs.Filter = string.Format("ProductName LIKE '*{0}*'", textBox1.Text);
}
}
this work just fine for me!
this.productBindingSource.Filter = null;