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;
Related
// fill from database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string readnamesquery = "select cwFullTitle from tbCowWorkers";
cn.Open();
SqlCommand cmd = new SqlCommand(readnamesquery, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlUsers.DataSource = dt;
ddlUsers.DataValueField = "cwFullTitle";
ddlUsers.DataTextField = "cwFullTitle";
ddlUsers.DataBind();
cn.Close();
// insert selected value to database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string registerQuery = "insert into Depot (dTdeliveryName) values (N'"+ddlUsers.SelectedValue.ToString()+"')";
SqlCommand cmd = new SqlCommand(registerQuery, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
I fill a Dropdownlist from SQL Server, then send selected item to another table in SQL Server; but it send first item of Dropdownlist as selected item.
Selected item didn't change and returns default value.
The reason is obvious, you are filling the dropdown list and then inserting the record, so it is bound to take the first item of the DropdownList.
I would suggest you separate the code of filling the dropdown list in another function and do the insertion only on selected_index change (ddl_SelectedIndexChanged) of DropDownList. In this ddl_SelectedIndexChanged function just check the selected value of the drop-down list and insert it to your target table (please remember to not invoke the call the function to load/Fill Dropdown List which you are currently doing in the shared code snippet).
SomeThing Like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string readnamesquery = "select cwFullTitle from tbCowWorkers";
cn.Open();
SqlCommand cmd = new SqlCommand(readnamesquery, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlUsers.DataSource = dt;
ddlUsers.DataValueField = "cwFullTitle";
ddlUsers.DataTextField = "cwFullTitle";
ddlUsers.DataBind();
cn.Close();
}
}
protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
{
// insert selected value to database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string registerQuery = "insert into Depot (dTdeliveryName) values
(N'"+ddlUsers.SelectedValue.ToString()+"')";
SqlCommand cmd = new SqlCommand(registerQuery, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
Hope this Helps!
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Loading Dropdown by calling This.
LoadDdl();
}
}
//Load Dropdown From Database.
protected void LoadDdl(){
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string readnamesquery = "select cwFullTitle from tbCowWorkers";
cn.Open();
SqlCommand cmd = new SqlCommand(readnamesquery, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlUsers.DataSource = dt;
ddlUsers.DataValueField = "cwFullTitle";
ddlUsers.DataTextField = "cwFullTitle";
ddlUsers.DataBind();
cn.Close();
}
//Inserting Item to another table by selected index change.
protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
{
//Checking If it's not the default value.
if(ddlUser.SelectedIndex != -1){
// insert selected value to database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string registerQuery = "insert into Depot (dTdeliveryName) values
(N'"+ddlUsers.SelectedValue.ToString()+"')";
SqlCommand cmd = new SqlCommand(registerQuery, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
What i am trying to do is when a user selects a company from a comboBox then clicks the button the different text boxes are supposed to show the different data from the database.
This is what i have but it doesnt seem to work.
Any suggestions?
private void Edit_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT * FROM Companies", con);
DataTable dt = new DataTable();
adapt.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Name";
}
}
private void button3_Click(object sender, EventArgs e)
{
String company = comboBox1.SelectedItem.ToString();
String check = #"SELECT * FROM Companies WHERE Name=#name";
using (SqlConnection con = new SqlConnection(str))
using (SqlCommand cmd = new SqlCommand(check, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = company;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox1.Text = (reader["Name"].ToString());
textBox2.Text = (reader["PhNo"].ToString());
textBox3.Text = (reader["Email"].ToString());
textBox4.Text = (reader["Acc"].ToString());
textBox5.Text = (reader["Address"].ToString());
textBox6.Text = (reader["Suburb"].ToString());
textBox7.Text = (reader["PostCode"].ToString());
textBox8.Text = (reader["State"].ToString());
}
}
}
Update: the output of comboBox1.SelectedItem.ToString(); is System.Data.DataRowView so it seems to not be registering what the selected item is. How do i resolve this?
When the DataSource of your combo box is a DataTable, then the object in SelectedItem is of type DataRowView.
So to get a field, you can cast selected item to DataRowView and extract the field value this way:
var name = ((DataRowView)comboBox1.SelectedItem)["Name"].ToString();
In fact ((DataRowView)comboBox1.SelectedItem)["FieldName"] is of type object and you should cast the field to the desired type.
Try this
String check = "SELECT * FROM Companies WHERE Name=#name";
using (SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=ABCD;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand(check, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = comboBox1.SelectedItem.ToString();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox1.Text = reader["Name"].ToString();
textBox2.Text = reader["PhNo"].ToString();
textBox3.Text = reader["Email"].ToString();
textBox4.Text = reader["Acc"].ToString();
textBox5.Text = reader["Address"].ToString();
textBox6.Text = reader["Suburb"].ToString();
textBox7.Text = reader["PostCode"].ToString();
textBox8.Text = reader["State"].ToString();
}
}
Make sure your connectionstring is proper. Also Have you checked value of comboBox1.SelectedItem.ToString() and same is present in db?
If you are populating drop down from database then refer this: System.Data.DataRowView in DropDownList
Updated:
private void ComboBoxBinding()
{
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT Name,Id FROM Companies", con);
DataTable dt = new DataTable();
adapt.Fill(dt);
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Id";
comboBox1.DataSource = dt;
comboBox1.DataBind();
}
}
You can call this function either in page load or in class constructor.
Try the code below it will work,the thing that you are missing is you are not setting the ValueMember property of your combo box.
Suggestion :
1.Debug your code and make sure that your query is correct and your able to getting the value right values from data source.
2.Make sure that your columns names in your database table are exactly same as you are setting in your combo box display member and value member
using (SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=\"Student Extended\";Integrated Security=True"))
{
SqlCommand command = new SqlCommand
{
Connection = connection,
CommandText = "SELECT DepartmentId,DepartmentName FROM dbo.TblDepartment"
};
SqlDataAdapter adpater = new SqlDataAdapter(command);
DataTable table = new DataTable();
adpater.Fill(table);
if (txtStdDeptName != null)
{
txtStdDeptName.DataSource = table;
txtStdDeptName.DisplayMember = "DepartmentName";
txtStdDeptName.ValueMember = "DepartmentId";
}
}
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);
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
In the first class i have a combobox and i am fetching its value from database and i have shown "Select Project Name" on page load in combobox.I want to insert its value only when user selects option from dropdown and insert nothing if user did not choose any option.
Now the problem is that the first name in the dropdown gets inserted on button click.without choosing any option.I want that if user did not choose any name value from dropdown nothing should get inserted.
can anyone help me..?
Assuming that datatype of ID column is int:
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
//begin adding line
DataRow row = table.NewRow();
row["project_name"] = "Select Project Name";
row["ID"] = 0;
table.Rows.InsertAt(row, 0);
//end adding line
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
if(combo_status.SelectedValue == 0)
{
return; //do nothing if user didn't select anything in combobox, you can change this line of code with whatever process you want
}
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
Hope this will help you
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";
}