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
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();
}
}
I just bound my combobox to database but it is not showing me values. However, I can see by the length of dropdown box that values are in it but aren't visible.
I just clicked on a value and it did work and took me to the next form. But how can I make those values visible?
private void StudentLogin_Load(object sender, EventArgs e)
{
con = new SqlConnection(constr);
con.Open();
cmd = new SqlCommand("select Std_ID from Student", con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Std_ID", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Load(reader);
metroComboBox1.ValueMember = "Std_ID";
metroComboBox1.DisplayMember = "Name";
metroComboBox1.DataSource = dt;
con.Close();
}
private void metroComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string ID = metroComboBox1.SelectedValue.ToString();
}
metroComboBox1.DataSource = dt;
metroComboBox1.ValueMember = "Std_ID";
metroComboBox1.DisplayMember = "Name";
metroComboBox1.DataBind();
I think the problem is in your query:
cmd = new SqlCommand("select Std_ID from Student", con);
does not contain the name. Instead try the following:
cmd = new SqlCommand("select Std_ID, Name from Student", con);
In order to display the ID instead of the name, put Std_ID as displaymamber as well.
I have a drop down list that binding data from database table and I can show it, but when I wanna show the data when I selected the drop down list value, it can't show anything
Here is my code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = GetData();
DropDownList1.DataTextField = "DEPT_NAME";
DropDownList1.DataValueField = "DEPT_NO";
DropDownList1.DataBind();
}
}
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = DropDownList1.SelectedValue;
using (SqlConnection conn = new SqlConnection(#"Data Source=server;Initial Catalog=DB;User ID=id;Password=pw"))
{
using (SqlCommand cmd = new SqlCommand("SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO =" +value, conn))
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
this.GridView1.Visible = true;
GridView1.DataSource = dr;
GridView1.DataBind();
dr.Close();
conn.Close();
}
}
}
DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(#"Data Source=server;Initial Catalog=DB;User ID=id;Password=pw"))
{
using (SqlCommand cmd = new SqlCommand("SELECT 'Please Select' AS DEPT_NAME , '000' AS DEPT_NO UNION SELECT DEPT_NAME , DEPT_NO FROM dept ORDER BY DEPT_NO ASC", conn))
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
}
return dt;
}
using (SqlCommand cmd = new SqlCommand("SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO = #value", conn))
cmd.Parameter.AddWithValue("#value",value);
Query ( "SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO =" +value) will work if DEPT_NO dataType is number
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";
}
}
private void Form1_Load(object sender, EventArgs e)
{
string Sql = "select project_name from tb_project";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(Sql, con);
con.Open();
OleDbDataReader DR = com.ExecuteReader();
while (DR.Read())
{
combo_status.Items.Add(DR[0]);
}
con.Close();
}
in this code i am fetching project name from a table in database and showing them in combobox but what i want is that in this is that in the table from where i am fetching project name there is a project id corresponding to that name...so i want project name to be displayed in combox and when i click on submit then it should insert project id corresponding to the project name choosen in combobox so how can i do that.....
Try this :
string Sql = "select project_name, project_id from tb_project";
con = new OleDbConnection(constr);
com = new OleDbCommand(Sql, con);
con.Open();
OleDbDataReader DR = com.ExecuteReader();
DataTable table = new DataTable();
table.Load(dr);
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember= "project_id";
As per my understanding, you want to insert the project id of the selected project name in some other table. To accomplish this you can use following code:
private void Form1_Load(object sender, EventArgs e)
{
string Sql = "select project_id, project_name from tb_project";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(Sql, con);
con.Open();
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(com);
da.Fill(ds);
combo_status.DataSource = ds.Tables[0];
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "project_id";
com.Dispose();
con.Close();
}
In this way you will find the project name using combo_status.SelectedText and you will find the project id using combo_status.SelectedValue. Now you can use it anywhere you want.
Use DisplayMember and ValueMember Of Combobox
// Fetch Both Project Name and Project Id
string Sql = "select project_name, project_id from tb_project";
con = new OleDbConnection(constr);
com = new OleDbCommand(Sql, con);
con.Open();
OleDbDataReader DR = com.ExecuteReader();
DataTable dt;
dt.Load(Dr);
combo_status.DataSource = dt; //Check it this works or not
combo_status.DisplayMember = "project_name";
combo_status.ValueMember= "project_id";
To get Project_id of Selected project_name
Int64 varproject_Id = Convert.ToInt64(combo_status.SelectedValue);
try this
while (DR.Read())
{
combo_status.Items.Add(DR.GetValues(0).toString());
}