Problems listing States on ComboBox (C#) - c#

i'm having troubles to list Brazillian States (The only States for now) on ComboBox2
I have one Database with 3 Tables , Paises(Contries), Estados(States) and Cidades(Cities), i'm trying to get the States using the Country Number and list it in the ComboBox2 but it isnt working.
My Code
private void Account_Create_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=WINDOWS-PC\SQLSERVER;Initial Catalog=World;Integrated Security=True");
string sql = "Select * from Paises";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sdr;
try
{
con.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
string Pais = sdr.GetString(1);
comboBox1.Items.Add(Pais);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=WINDOWS-PC\SQLSERVER;Initial Catalog=World;Integrated Security=True");
string sql = "Select Cod from Paises where NomePT = '" + comboBox1.Text + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sdr;
try
{
con.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
string Cod = sdr.GetValue(0).ToString();
lbl1.Text = Cod;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=WINDOWS-PC\SQLSERVER;Initial Catalog=World;Integrated Security=True");
string sql = "select Cod , Estados from Estados where PaisCod = " + lbl1.Text + "";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sdr;
try
{
con.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
string Cod = sdr.GetValue(0).ToString();
lbl2.Text = Cod;
string Estado = sdr.GetString(1);
comboBox2.Items.Add(Estado);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=WINDOWS-PC\SQLSERVER;Initial Catalog=World;Integrated Security=True");
string sql = "Select * from Cidades where Ci_Cod = " + lbl2.Text + "";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sdr;
try
{
con.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
string Cidade = sdr.GetString(1);
comboBox3.Items.Add(Cidade);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm kinda new with C# and Windows Forms, it's something on my code?

I have figured out how to make it work.
I can't explain exactly how i make it but that's the code :
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=WINDOWS-PC\SQLSERVER;Initial Catalog=World;Integrated Security=True");
string sql = "Select * from Paises";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sdr;
try
{
con.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
string Pais = sdr.GetString(4);
comboBox1.Items.Add(Pais);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=WINDOWS-PC\SQLSERVER;Initial Catalog=World;Integrated Security=True");
string sql = "Select Cod from Paises where Nome = '" + comboBox1.SelectedItem + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sdr;
try
{
con.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
string PaisCod = sdr.GetValue(0).ToString();
Cod.Text = PaisCod;
}
sdr.Close();
string a = "Select Estados from Estados where PaisCod = " + Cod.Text + "";
SqlCommand cm1 = new SqlCommand(a , con);
SqlDataReader sd1;
sd1 = cm1.ExecuteReader();
while(sd1.Read())
{
string aqw = sd1.GetString(0);
comboBox2.Items.Add(aqw);
}
sd1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=WINDOWS-PC\SQLSERVER;Initial Catalog=World;Integrated Security=True");
string b = "Select Cod from Estados where Estados = '" + comboBox2.Text + "'";
SqlCommand cmd = new SqlCommand(b , con);
SqlDataReader sdr;
try
{
con.Open();
sdr = cmd.ExecuteReader();
while(sdr.Read())
{
string Cod = sdr.GetValue(0).ToString();
Ci_Cod.Text = Cod;
}
sdr.Close();
string c = "Select Cidade from Cidades where Ci_Cod = " + Ci_Cod.Text + "";
SqlCommand cm1 = new SqlCommand(c , con);
SqlDataReader sd1;
sd1 = cm1.ExecuteReader();
while(sd1.Read())
{
string Cidades = sd1.GetString(0);
comboBox3.Items.Add(Cidades);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
(Yeh, some of my variables are a mess)
So, basicaly, when the form loads, the Countries table load on CheckBox1.
When the user select a country on CheckBox the Label Cod recieves the Country Code, after that, the CheckBox2 automaticaly select the States where the "PaisCod" is equal to the Country Code, when the State is selected the Label "Ci_Cod" recieves the State Code, and finally, the CheckBox3 select the Cities that the Code is equal to the City code. Sorry if this is confusing, comment if you don't understand it.

Related

How to update a quantity of an item if it already exists in database

I have a productstbl table consisting of Name,Quantity and other attributes.
When I want to buy a new item that is already present in productstbl table I need to update the Quantity.
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Productstbl WHERE Name = #name", con);
con.Open();
cmdCount.Parameters.AddWithValue("#name", NameBox.Text);
int count = (int)cmdCount.ExecuteScalar();
con.Close();
if (count > 0)
{
SqlCommand cmd = new SqlCommand("SELECT Qunatity FROM Productstbl WHERE Name = #name, Quantity = #quantity", con);
con.Open();
cmd.Parameters.AddWithValue("#name", NameBox.Text);
int ExistingQTY = (int)cmdCount.ExecuteScalar(); // I get error here
}
cmd = new SqlCommand("INSERT INTO Historytbl (Name, Date, Price, Quantity, Total_Price, Sup_Name, Process, Retail_Price) VALUES (#name, #date, #price, #quantity, #total_price, #sup_name, #process, #retail_price)", con);
con.Open();
cmd.Parameters.AddWithValue("#name", NameBox.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#price", PriceBox.Text);
cmd.Parameters.AddWithValue("#quantity", ExistingQTY);
cmd.Parameters.AddWithValue("#total_price", TotalPriceBox.Text);
cmd.Parameters.AddWithValue("#sup_name", comboBox1.Text);
cmd.Parameters.AddWithValue("#process", "buy");
cmd.Parameters.AddWithValue("#retail_price", RetailPriceBox.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record inserted successfully");
DisplayData();
ClearData();
If you want to update a quantity of a product, it is best for to get the quantity in the database if it already exists the database.
I make a code example, you can have a look.
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("Juice");
comboBox1.Items.Add("Apple");
comboBox1.Items.Add("Milk");
ShowData();
}
public void ShowData()
{
string connstr = "connstr";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
string cmd = "select * from Product";
DataSet set = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd, connection);
adapter.Fill(set);
dataGridView1.DataSource = set.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
string connstr = "connstr";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Product WHERE Name = #Name", connection);
cmdCount.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
int count = (int)cmdCount.ExecuteScalar();
int i = 0;
if(count>0)
{
SqlCommand command = new SqlCommand("SELECT Quantity FROM Product WHERE Name = #Name",connection);
command.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
i = Convert.ToInt32(reader["Quantity"]);
}
}
SqlCommand updatecmd = new SqlCommand("Update Product set Quantity=#Quantity, Date=#Date where Name=#Name",connection);
updatecmd.Parameters.AddWithValue("#Quantity", i + numericUpDown1.Value);
updatecmd.Parameters.AddWithValue("#Date", DateTime.Now);
updatecmd.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
updatecmd.ExecuteNonQuery();
dataGridView1.DataSource = null;
ShowData();
MessageBox.Show("Update successfully");
}
else
{
SqlCommand insertcmd = new SqlCommand("insert into Product(Name,Quantity,Date,Price)values(#Name,#Quantity,#Date,#Price)",connection);
insertcmd.Parameters.AddWithValue("Name", comboBox1.SelectedItem.ToString());
insertcmd.Parameters.AddWithValue("#Quantity",numericUpDown1.Value);
insertcmd.Parameters.AddWithValue("#Date",DateTime.Now);
insertcmd.Parameters.AddWithValue("Price",Convert.ToInt32(textBox1.Text));
insertcmd.ExecuteNonQuery();
dataGridView1.DataSource = null;
ShowData();
MessageBox.Show("Insert successfully");
}
connection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedItem.ToString()== "Juice")
{
textBox1.Text = "10";
}
if (comboBox1.SelectedItem.ToString() == "Apple")
{
textBox1.Text = "5";
}
if (comboBox1.SelectedItem.ToString() == "Milk")
{
textBox1.Text = "8";
}
}
Tested Result:

C# multi valued combo box value to SQL Server database

private void filljobid()
{
try
{
string jobid = "";
int newjobid, oldjobid;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("SELECT MAX(job_id) FROM job", con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
jobid = reader[0].ToString();
}
oldjobid = int.Parse(jobid.ToString());
newjobid = oldjobid + 1;
jobidtextbox.Text = newjobid.ToString();
}
catch (Exception)
{
MessageBox.Show("Error while connecting");
}
}
private void fillcustomercombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT customer_id,(first_name + ' ' + last_name + ' - ' + contact) AS CUSTOMERNAME FROM customer", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
customeridcombobox.DataSource = ds.Tables[0];
customeridcombobox.DisplayMember = "CUSTOMERNAME";
customeridcombobox.ValueMember = "customer_id";
cmd.ExecuteReader();
con.Close();
// CODE FOR DISPLAYING multiple values in another way, but not sure how to retrieve data from this function
// for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
// {
// customeridcombobox.Items.Add(ds.Tables[0].Rows[i][0] + " - " + ds.Tables[0].Rows[i][1] + " " + ds.Tables[0].Rows[i][2]);
// }
}
private void filldepotcombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT depot_id,(branch_name + ' - ' + region_name + ' - ' + location) AS DEPOTNAME FROM depot", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
depotidcombobox.DataSource = ds.Tables[0];
depotidcombobox.DisplayMember = "DEPOTNAME";
depotidcombobox.ValueMember = "depot_id";
cmd.ExecuteReader();
con.Close();
}
private void filljobtypecombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT job_type FROM jobtype", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
jobtypecombobox.DisplayMember = "job_type";
jobtypecombobox.ValueMember = "job_type";
jobtypecombobox.DataSource = ds.Tables[0];
cmd.ExecuteReader();
con.Close();
}
private void loadingcomboboxesdata_Load(object sender, EventArgs e)
{
fillcustomercombox();
filljobid();
filldepotcombox();
filljobtypecombox();
}
private void addnewjobbutton_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMoversDB;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into job (start_location, end_location, depot_id, job_type, customer_id,) values ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "','" + depotidcombobox.Text + "','" + jobtypecombobox.Text + "','" + customeridcombobox.Text + "')";
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Added new job");
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
What I'm trying to achieve is basically take the users selected value which is displayed in the combo box which is valuemember and then insert it into the database. Right now I get the error when I try to insert the data into the database. When I do the combo box with a single value it works fine but it doesn't work when I do it with multiple values.
Could someone close this question. I managed to solve my own question. I dont know if this solution is considered good but here you go.
private void addnewjobbutton_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO job(start_location, end_location, depot_id, job_type, customer_id) VALUES ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "',#3,#4, #5)"))
{
cmd.Connection = con;
//cmd.Parameters.AddWithValue("#1", startlocationtxtbox.SelectedText);
//cmd.Parameters.AddWithValue("#2", endlocationtxtbox.SelectedText);
cmd.Parameters.AddWithValue("#3", depotidcombobox.SelectedValue);
cmd.Parameters.AddWithValue("#4", jobtypecombobox.SelectedValue);
cmd.Parameters.AddWithValue("#5",customeridcombobox.SelectedValue);
con.Open();
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
}

Reading tables from SQL Server Express database

I am trying to read my tables that are contained within my database in SQL Server Express, but it keeps coming up empty. What is it that am doing wrong?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Updated but still empty:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try {
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con2 = new SqlConnection(connectionString);
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
comboBox1.Items.Add((string)dr2[0]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}}
Latest Updated code. Think I figured it but still showing empty:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try {
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con2 = new SqlConnection(connectionString);
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
string Dtables = dr2.GetString(dr2.GetOrdinal("TABLE_NAME"));
comboBox1.Items.Add(Dtables);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}}
Full class:
namespace unique_database{ public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
string query = "CREATE TABLE [dbo].[" + textBox1.Text + "](" + "[Code] [varchar] (13) NOT NULL," +
"[Description] [varchar] (50) NOT NULL," + "[NDC] [varchar] (50) NULL," +
"[Supplier Code] [varchar] (38) NULL," + "[UOM] [varchar] (8) NULL," + "[Size] [varchar] (8) NULL,)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
SqlConnection con = new SqlConnection("Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True");
string filepath = textBox2.Text; //"C:\\Users\\jdavis\\Desktop\\CRF_105402_New Port Maria Rx.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = textBox1.Text;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "CSV files (*.csv)|*.csv|XML files (*.xml)|*.xml";
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox2.Text = openFileDialog.FileName;
}
}
private void FillCombo()
{
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
int col = dr2.GetOrdinal("TABLE_NAME");
comboBox1.Items.Add(dr2[col].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Ok, first, don't use comboBox1_SelectedIndexChanged to fill comboBox1.
use YourForm.OnLoad event, the form constructor, or click a button, but don't use SelectedIndexChanged to fill itself, because you're executing this procedure every time you select one item of comboBox1.
To get column index simply use: dr2.GetOrdinal("TABLE_NAME");
private void FillCombo()
{
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
int col = dr2.GetOrdinal("TABLE_NAME");
comboBox1.Items.Add(dr2[col].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Use ExecuteReader() instead of ExecuteNonQuery().then Use SqlDataReader() for get result.

inserting radio button value in database in c#.net

private void btnUpdate_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
if (radioButton1.Checked)
{
string Sql_radio = "Insert Into tb1(name)Values ('Yes')";
}
if (radioButton2.Checked)
{
string Sql_radio = "Insert Into tb1(name)Values ('no')";
}
OleDbCommand cmd = new OleDbCommand(Sql_radio, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
hello.. i am developing a winform application, now i have two radio buttons as you can see in the above code.
i want that if user selects radiobutton1 then yes should get inserted in the database and if user selects radiobutton2 then it should insert no in the databse.
i have aplied following condition but it is giving an error that the
name Sql_radio does not exist in the current context
can anyone please tell me the correct way to do the above code?
You will have to declare string Sql_radio globally in the code for btnUpdate_Click function.
See following:
private void btnUpdate_Click(object sender, EventArgs e)
{
string Sql_radio="";
OleDbConnection con = new OleDbConnection(constr);
con.Open();
if (radioButton1.Checked)
{
Sql_radio = "Insert Into tb1(name)Values ('Yes')";
}
if (radioButton2.Checked)
{
Sql_radio = "Insert Into tb1(name)Values ('no')";
}
OleDbCommand cmd = new OleDbCommand(Sql_radio, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
private void btnUpdate_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string Sql_radio = "";
if (radioButton1.Checked)
{
Sql_radio = "Insert Into tb1(name)Values ('Yes')";
}
if (radioButton2.Checked)
{
Sql_radio = "Insert Into tb1(name)Values ('no')";
}
OleDbCommand cmd = new OleDbCommand(Sql_radio, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
Scope of Sql_radio is expired after the if snippets. Move the declaration to method scope and everything will be fine.
Declare your string outside of if condition ,
private void btnUpdate_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string Sql_radio = String.Empty;
if (radioButton1.Checked)
{
Sql_radio = "Insert Into tb1(name)Values ('Yes')";
}
if (radioButton2.Checked)
{
Sql_radio = "Insert Into tb1(name)Values ('no')";
}
OleDbCommand cmd = new OleDbCommand(Sql_radio, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
Declare string Sql_radio out of If
Try
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string Sql_radio = "";
if(RadioButton1.Checked)
{
Sql_radio = "Insert Into tb1(name)Values ('Yes')";
}
else if(RadioButton2.Checked)
{
Sql_radio = "Insert Into tb1(name)Values ('No')";
}
OleDbCommand cmd = new OleDbCommand(Sql_radio, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
catch(Exception Ex)
{
MessageBox.Show(Ex.Message);
}
Put the string Sql_radio out of if condition as mentioned below :
private void btnUpdate_Click(object sender, EventArgs e)
{
var con = new OleDbConnection(constr);
con.Open();
var Sql_radio = string.Empty;
if (radioButton1.Checked)
{
Sql_radio = "Insert Into tb1(name)Values ('Yes')";
}
if (radioButton2.Checked)
{
Sql_radio = "Insert Into tb1(name)Values ('no')";
}
var cmd = new OleDbCommand(Sql_radio, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}

How to populate a DataGridView by selecting any table from combo box

I have used the following code for displaying names of my SQL db tables in a combo box.
Now I want that when I click on any of these table names from the combo box, my DGV populates with that table's contents.
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Then I used the following code for populating my DGV but it's not working; please help.
private void PopulateGridView()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedText;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
PopulateGridView(comboBox1.SelectedValue.ToString());
}
}
just try this:
update your code in the Form Load with below:
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "table_name";
comboBox1.ValueMember = "table_name";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
so basically you have added one extra line comboBox1.ValueMember = "table_name";
and make your PopulateGridView method like this:
private void PopulateGridView(string tblName)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + tblName;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
it has to work.
Also, I see, you are creating SqlConnection object everywhere, including SqlCommand and SqlDataAdapter.
try to wrap them up in static methods i.e.
- public static SqlConnection OpenConnection()
- public static DataTable ExecuteSelectQuery(string Query)
- public static bool ExecuteModifyQuery(string Query)
try to write as less amount of code as you can.
Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
string strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedValue;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Categories