Visual c# relatively dynamic comboboxes - c#

I have two related comboboxes, combobox1 populate the items of combobox2. In combobox1 selectIndexChanged event I have this code but i have error Unknown column 'System.Data.DataRowView' in 'where clause'.
I tried to put this code in the SelectionChangeCommitted at first selection, it populate the right items, but my second selection i have error in comboBox2.Items.Clear(); states Items collection cannot be modified when the DataSource property is set. :( what to do.?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sql;
if (comboBox1.SelectedIndex >= 0)
{
comboBox2.Items.Clear();
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}
}
Here's how i populate combobox1
private void cbMun()
{
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("SELECT munname,idmun from municipality", conn);
DataTable cbMun = new DataTable();
adapter.Fill(cbMun);
comboBox1.DataSource = cbMun;
comboBox1.DisplayMember = "munname";
comboBox1.ValueMember = "idmun";
}

while cbMun function is filling the combobox it will call combobox selected index change event directly , so to work around this define bool value comboisloading = true and modify your code such like below :
private void cbMun()
{
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("SELECT munname,idmun from municipality", conn);
DataTable cbMun = new DataTable();
adapter.Fill(cbMun);
comboBox1.DataSource = cbMun;
comboBox1.DisplayMember = "munname";
comboBox1.ValueMember = "idmun";
comboisloading = false;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboisloading)
return;
string sql;
if (comboBox1.SelectedIndex >= 0)
{
comboBox2.Items.Clear();
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}
}

I just placed my code in comboBox1_SelectionChangeCommitted not in comboBox1_SelectedIndexChanged event since comboBox1.SelectedValue is still not generated not unless the user committed its changes to the items. Also my Items collection cannot be modified when the DataSource property is set error from comboBox2.Items.Clear(); i just deleted this line of code. I still clears and replace my combobox2 items properly. Hmm.. Since i used to clear comboboxes in vb..I wonder.
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
string sql;
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}

Related

fill grid view in c#

I am new in using visual studio and ADO.NET. I want to display result from sqlserver database in data gridview.
This is my code but it does not fill data to gridview.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand Cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(Cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
SqlDataReader reader = Cmd.ExecuteReader();
dt.Load(reader);
dataGridView1.DataSource = dt;
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
Why are you binding to grid two times?
If your application is ASP.NET Webforms and you are trying to bind the GridView(ID for the GridView is "dataGridView1"), then make your binding to single time and to bind data for GridView you need to use dataGridView1.DataBind(); after dataGridView1.DataSource = dt;
If your application is WindowsForms application then modify your code like below
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
string connectionString = "Define your connection string here";
using(SqlConnection con = new SqlConnection(connectionString ))
{
SqlCommand cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
}

cascading comboBox in windows form using c#

I am trying to Fill Combobox2 on combobox1 selectedText changed from the same table in windows form application. I am using sql serevr 2008 database. I am unable to fill combobox2 on combobox selected text changed.
Here is what i have tried:
private void Purchase_Load(object sender, EventArgs e)
{
fillName();
comboBoxName.SelectedIndex = -1;
}
private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxName.SelectedText != "")
{
fillMake();
}
}
private void fillName()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Name from Item";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Make";
}
private void fillMake()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Make from Item Where Item_Name='" + comboBoxName.SelectedText + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Make";
comboBoxName.ValueMember = "Item_Name";
comboBoxName.SelectedIndex = -1;
comboBoxName.Text = "Select";
}
Sql server table for Items
Item_Code Item_Name Item_Make Item_Price UnitofMeasurement
Cable anchor 45.0000 meter
Cable polycab 30.0000 meter
Button anchor 15.0000 unit
Button havells 20.0000 unit
Switch cona 70.0000 unit
I have searched for solution but was unfortunate.
please help me out.
Thanks in advance.
It's a little difficult to figure out what you're trying to do, but it sounds like you are trying to populate a second combo box (comboBoxMake?) depending on what is selected in comboBoxName. I am basing this answer on that assumption. Apologies if I have this wrong.
There are lot of things that need attention in this code. Let's look at fillName() first.
private void fillName()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Name from Item";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Make";
}
You need to Dispose() your database objects. This can be accomplished pretty cleanly with using { .. } blocks.
You don't need to manually open the connection; filling the table with the data adapter
does this automatically.
You don't need the call to ExecuteNonQuery().
You should use the SqlDataAdapter constructor overload that takes a command object, since you have already manually created the command.
Finally, based on my assumption of your goal I have added a distinct to your query so it only gets the unique Item_Names.
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
On to fillMake(). The same suggestions apply that I noted above. Additionally:
Parameterize your SQL. Parameterize your SQL. Not only is this far, far safer than concatenating your SQL together, it is much cleaner. Seriously, read about SQL injection: http://en.wikipedia.org/wiki/SQL_injection
The fillMake() method in your original post seems to be repopulating comboBoxName. Is this correct? You mention two combo boxes but your code only references one. I am assuming you mean to populate another combo box (comboBoxMake?) here:
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name = #item_name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#item_name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.DisplayMember = "Item_Make";
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.SelectedIndex = -1;
comboBoxMake.Text = "Select";
}
}
}
}
Lastly, change the code in the event handler so it looks at the Text rather than the SelectedText property:
private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text)) // Text instead of SelectedText
{
fillMake();
}
}

Why Name not showing in textbox based on combobox selected id

I using below code but it's not showing name in textbox.\
private void AllotLeaves_Load(object sender, EventArgs e)
{
display();
}
private void display()
{
SqlConnection conn = new SqlConnection(#"Data Source=.......");
conn.Open();
SqlDataAdapter ad = new SqlDataAdapter("select *from Emp_Details", conn);
DataSet ds = new DataSet();
ad.Fill(ds, "Emp_Details");
cballotid.DataSource = ds.Tables["Emp_Details"].DefaultView;
cballotid.DisplayMember = "ID";
cballotid.ValueMember = "ID";
}
private void cballotid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=......");
conn.Open();
SqlCommand command = new SqlCommand("select Name from Emp_Details where ID=#ID", conn);
command.Parameters.AddWithValue("#ID", cballotid.Text);
Object temp = command.ExecuteScalar(); // this returns the first value of the select statement.
if (temp != null)
txtallotname.Text = temp.ToString();
conn.Close();
}
Try this
cballotid.DisplayMember = "Name";
cballotid.ValueMember = "ID";
cballotid.BindingContext = this.BindingContext;
Reference: ListControl.DisplayMember Property
You have to change this
cballotid.DisplayMember = "ID";
cballotid.ValueMember = "ID";
to
cballotid.DisplayMember = "name of field youd like to display";
cballotid.ValueMember = "ID";
Change this line as below:-
command.Parameters.AddWithValue("#ID", cballotid.SelectedValue);

Load data from SQL to combo and save selected value

i try to load values from sql database to combobox and after button click i want to save selected value of combobox to variable.
This is my code:
SqlConnection con = new SqlConnection(connectionstring);
con.Open();
string strCmd = "select id,Prijmeni from Osoba";
SqlCommand cmd3 = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Prijmeni";
comboBox1.ValueMember = "id";
comboBox1.Enabled = true;
cmd3.ExecuteNonQuery();
con.Close();
private void Ulozit_Click(object sender, EventArgs e)
{
//How i could save selected value of combobox to variable Value1 ???
}
Have you any ideas please?
You can save the selected value by:
var Value1 = comboBox1.SelectedValue;

Populating a combolist automatically with data from SQL Server database

Can anyone help please, I am trying to populate the data automatically to my combobox without having to push any button, but by the dropdown control.....
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.AllowDrop == false)
{
SqlConnection conn = new SqlConnection("Data Source=localhost; database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Problem FROM PROBLEMT", conn);
DataTable dt = new DataTable();
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = new SqlCommand("SELECT Problem FROM PROBLEMT", conn);
ad.Fill(ds, "Problem");
dataGridView1.DataSource = dt;
//Biding the data with the control
BindingSource bs = new BindingSource();
bs.DataSource = ds;
bs.DataMember = "Problem";
DataGridView dvg = new DataGridView();
this.Controls.Add(dvg);
dvg.DataSource = bs;
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox1.Items.Add(dt.Rows[i]["Problem"]);
}
}
else
{
}
}
you are missing a } and I hardly believe that SelectedIndexChanged is the best place to populate a combobox. Since obviously you are learning, try to put your code on a button, once it is working fine from the click of the button, you can look for a better place to it, like the form load for example.
also what exactly is the problem? does it give an error?
first create method for fetching data and load in combobox like this
protected void LoadCombo()
{
SqlConnection conn = new SqlConnection("Data Source=localhost;database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Problem FROM PROBLEMT", conn);
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = new SqlCommand("SELECT Problem FROM PROBLEMT", conn);
ad.Fill(ds, "Problem");
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
for (int X = 0; X <= ds.Tables[0].Rows.Count - 1; X++)
{
comboBox1.Items.Add(ds.Tables[0].Rows[X]["Problem"].ToString());
}
}
now on page_load call this method
protected void Page_Load()
{
if(ispostback)
{
}
else
{
LoadCombo();
}
}
Answer to the question on how to populate a combobox automatically:
private void Form3_Load(object sender, EventArgs e)
{
using (SqlConnection sc = new SqlConnection())
{
sc.ConnectionString= "database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30";
sc.Open();
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable data = new DataTable();
sda.SelectCommand = new SqlCommand("SELECT ID, TypeProblem FROM eL_Section", sc);
sda.Fill(data);
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "ID";
comboBox1.DataSource = data;
comboBox2.ValueMember = "TypeProblem";
comboBox2.DisplayMember = "TypeProblem";
comboBox2.DataSource = data;
}
}
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = "database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30";
cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter())
{
DataTable dat = new DataTable();
da.SelectCommand = new SqlCommand("SELECT UserName FROM UserT", cn);
da.Fill(dat);
comboBox3.ValueMember = "UserName";
comboBox3.DisplayMember = "UserName";
comboBox3.DataSource = dat;
}
}
// TODO: This line of code loads data into the 'knowledgeEssentialsDataSet.ProblemT' table. You can move, or remove it, as needed.
this.problemTTableAdapter.Fill(this.knowledgeEssentialsDataSet.ProblemT);
}

Categories