protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["project"].ConnectionString.ToString());
conn.Open();
string arun = "UPDATE [RECEIVE] SET [RDDF2]=#RDFF2 WHERE [OIESN]=#SRT";
string SR2 = TextBox1.Text;
int SR = int.Parse(TextBox1.Text);
string SR1 = TextBox9.Text;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = arun;
cmd.Parameters.AddWithValue("#SRT", SR);
cmd.Parameters.AddWithValue("#RDFF2", SR1);
cmd.ExecuteNonQuery();
conn.Close();
}
It is not showing error but not updating in database.
Try the code below:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["project"].ConnectionString.ToString());
string arun = "UPDATE [RECEIVE] SET [RDDF2]=#RDFF2 WHERE [OIESN]=#SRT";
string SR2 = TextBox1.Text;
int SR = int.Parse(TextBox1.Text);
string SR1 = TextBox9.Text;
using (SqlCommand SqlCmd = new SqlCommand(arun, conn))
{
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#SRT", SqlDbType.Int).Value = SR;
cmd.Parameters.Add("#RDFF2", SqlDbType.VarChar).Value = SR1;
cmd.ExecuteNonQuery();
conn.Close();
}
}
Related
Execute.nonquery is giving the error of must declare the scalar variable.. please tell me solution
private void btndelete_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
string query = "delete stu_data where Reg_no=#regNo";
SqlDataAdapter sda = new SqlDataAdapter(query,con);
sda.SelectCommand.Parameters.AddWithValue("#regNo", textBox1.Text.ToString());
sda.DeleteCommand = con.CreateCommand();
sda.DeleteCommand.CommandText = query;
sda.DeleteCommand.ExecuteNonQuery();
}
}
}
Here you have a nice delete example:
try
{
using (var sc = new SqlConnection(ConnectionString))
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "DELETE FROM excludes WHERE word = #word";
cmd.Parameters.AddWithValue("#word", word);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
Box.Text = "SQL error" + e;
}
Or if you are using SqlDataAdapter:
command = new SqlCommand("DELETE FROM Customers WHERE CustomerID = #CustomerID", connection);
// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add("#CustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
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.
Can someone help me out?
I just get as result tb_localidade: System.Data.SqlClient.SqlDataReader
Why? Here is the code:
private void btn_normalizar_Click(object sender, EventArgs e)
{
//connection string - one or other doenst work
//SqlConnection conn = new SqlConnection("DataSource=FRANCISCO_GP;Initial Catalog=Normalizacao;Integrated Security=True;");
SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString);
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader leitor = cmd.ExecuteReader();
tb_localidade.Text = leitor.ToString();
conn.Close();
}
You can do this by calling Read() on your data reader and assigning the results:
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
Another note is that using a using block for your SqlConnection and SqlCommand objects is a good habit to get into.
Note: this is assigning the result to the tb_localidade.Text for every row in the resultset. If you are only intending for this to be one record, you might want to look into .ExecuteScalar() instead (see below).
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
tb_localidade.Text = cmd.ExecuteScalar().ToString();
}
}
}
before execute "executeReader()" then you must read to get results.
Improvement on Siyual's response. You're only looking for a single result, and this explicitly disposes both the connection and the datareader.
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using(SqlCommand cmd = new SqlCommand(sql, conn)) {
using(SqlDataReader leitor = cmd.ExecuteReader())
{
if (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
}
you should just this
SqlDataReader leitor = cmd.ExecuteReader();
string res="";
while(leitor.Read())
{
res=leitor.GetValue(0).ToString()///////if in sql it is varchar or nvarshar
}
tb_localidade.Text = res;
actully datareader is a 1d table and we can access to this with GetValue or GetInt32 or ...
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.
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");
}