Must Declare a static variable in c# Winfoms - c#

I have got an error that you must have to declare a static variable #campus_id. I don't know how to declare and where to declare and what it means to declare a static variable. Help me please!
private void btnSave_Click(object sender, EventArgs e)
{
try
{
CS = ConfigurationManager
.ConnectionStrings["UMSdbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand(
"SELECT ISNULL(MAX(campus_id),0)+1 FROM Campus", con);
cmd.CommandType = CommandType.Text;
tbCampusID.Text = cmd.ExecuteScalar().ToString();
using (SqlCommand cmd1 = new SqlCommand(
"INSERT INTO Campus (campus_id,campus_name)VALUES(#camp_id,camp_name)", con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#campus_id", tbCampusID.Text);
cmd1.Parameters.AddWithValue("#campus_name", tbCampusName.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Saved");
}
}
}
catch (Exception)
{
}
}

The parameter names in your SQL query and in the call to Parameters.AddWithValue must match:
using (SqlCommand cmd1 = new SqlCommand(
"INSERT INTO Campus (campus_id, campus_name) VALUES(#campus_id, #campus_name)", con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#campus_id", tbCampusID.Text);
cmd1.Parameters.AddWithValue("#campus_name", tbCampusName.Text);
cmd1.ExecuteNonQuery();
con.Close();
}

You are adding value to a placeholder that is not yet defined. see this statement
cmd1.Parameters.AddWithValue("#campus_id", tbCampusID.Text); Here you are using campus_id as placeholder and take a look into the insert query, ie., INSERT INTO Campus (campus_id,campus_name)VALUES(#camp_id,camp_name). and there the placeholder is camp_id and that causing the error; use like this:
string querySql = "INSERT INTO Campus (campus_id, campus_name) VALUES(#camp_id, #campus_name)"
using (SqlCommand cmd1 = new SqlCommand(querySql, con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#camp_id", tbCampusID.Text);
cmd1.Parameters.AddWithValue("#campus_name", tbCampusName.Text);
cmd1.ExecuteNonQuery();
con.Close();
}

Related

Trying to add a C# variable into a row in an existing table using windows form [duplicate]

I'm able to delete, insert and update in my program and I try to do an insert by calling a created stored procedure from my database.
This button insert I made works well.
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dc.Con);
SqlCommand cmd = new SqlCommand("Command String", con);
da.InsertCommand = new SqlCommand("INSERT INTO tblContacts VALUES (#FirstName, #LastName)", con);
da.InsertCommand.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
da.InsertCommand.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
con.Close();
dt.Clear();
da.Fill(dt);
}
This is the start of the button that calls the procedure named sp_Add_contact to add a contact. The two parameters for sp_Add_contact(#FirstName,#LastName). I searched on google for some good examples but found nothing interesting.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dc.Con);
SqlCommand cmd = new SqlCommand("Command String", con);
cmd.CommandType = CommandType.StoredProcedure;
???
con.Open();
da. ???.ExecuteNonQuery();
con.Close();
dt.Clear();
da.Fill(dt);
}
It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.
Also, use a using for all disposable objects, so that you are sure that they are disposed properly:
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
You have to add parameters since it is needed for the SP to execute
using (SqlConnection con = new SqlConnection(dc.Con))
{
using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", txtfirstname.Text);
cmd.Parameters.AddWithValue("#LastName", txtlastname.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
cmd.Parameters.Add(String parameterName, Object value) is deprecated now. Instead use cmd.Parameters.AddWithValue(String parameterName, Object value)
Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value)
There is no difference in terms of functionality. The reason they
deprecated the cmd.Parameters.Add(String parameterName, Object value) in favor of AddWithValue(String parameterName, Object value) is to give more
clarity. Here is the MSDN reference for the same
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
As an alternative, I have a library that makes it easy to work with procs: https://www.nuget.org/packages/SprocMapper/
SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
sqlAccess.Procedure()
.AddSqlParameter("#FirstName", SqlDbType.VarChar, txtFirstName.Text)
.AddSqlParameter("#FirstName", SqlDbType.VarChar, txtLastName.Text)
.ExecuteNonQuery("StoredProcedureName");
public void myfunction(){
try
{
sqlcon.Open();
SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sqlcon.Close();
}
}
The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.
A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :
CREATE PROCEDURE SPCOUNTRY
#COUNTRY VARCHAR(20)
AS
SELECT PUB_NAME FROM publishers WHERE COUNTRY = #COUNTRY
GO
The above stored procedure is accepting a country name (#COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("#COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
The above code passing country parameter to the stored procedure from C# application.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPCOUNTRY";
param = new SqlParameter("#COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
}
connection.Close();
}
}
}
Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money
public void SaveTransaction(Transaction transaction)
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
{
using (var cmd = new SqlCommand("spAddTransaction", con))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
cmd.Parameters.AddWithValue("#" + prop.Name, prop.GetValue(transaction, null));
con.Open();
cmd.ExecuteNonQuery();
}
}
}

how to get a content from textboxes in a database table with a Button click event?

IWhat i wanna do
So I tried this code
but it coudnt get a connection with the Database. I the connection string is correct
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into [kunde]Vorname()values(#nm)";
cmd.Parameters.AddWithValue("#nm", Vorname.Text);
cmd.Connection = con;
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "insert into [kunde]Nachname()values(#nmm)";
cmdd.Parameters.AddWithValue("#nmm", Nachname.Text);
cmdd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Dateien bitte");
}
follow the following code. It inserts two columns into a table (tableName). Maintain proper space in SQL query as showing in below sample code. ALso, it's best practice to keep the code in a try-catch block to capture any error that occurs during DB operation.
try
{
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into tableName(column1,column2) values(#nm,#nmm)";
cmd.Parameters.AddWithValue("#nm", Vorname.Text);
cmd.Parameters.AddWithValue("#nmm", Nachname.Text);
cmd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Dateien bitte");
}
}
catch (Exception ex)
{
MessageBox.Show("Error:"+ex.ToString());
}

Insert statement not working

I'm creating a small c# application using VS local database these are my commands for inserting its not showing any error but the fields are not inserted in the database.
public partial class Form1 : Form
{
SqlCeConnection cn=new SqlCeConnection("Data Source=|DataDirectory|\\Database1.sdf");
public Form1()
{
InitializeComponent();
cn.Open();
SqlCeCommand cmd;
string sql = "insert into sales values (#item, #price)";
try
{
cmd = new SqlCeCommand(sql, cn);
cmd.Parameters.AddWithValue("#item", "7777");
cmd.Parameters.AddWithValue("#price"," 2");
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}
}
Just one more question when deploying this application to the user should I install anything on the client machine??
Try something like this
//include column names
string sql = "insert into sales(Item,Price) values (#item, #price)";
try
{
cmd = new SqlCeCommand(sql, cn);
cmd.Parameters.AddWithValue("#item", 7777); //int instead of string
cmd.Parameters.AddWithValue("#price", 2); //int instead of string
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}

Why does this UPDATE command not update the data, even though there is no error?

I have a users table having fields uname, ushortname and pswd as well ucode as primary key.
The following UPDATE is not working:
protected void Page_Load(object sender, EventArgs e)
{
string uname = Request.QueryString["uname"];
string ucode = Request.QueryString["ucode"];
if (!string.IsNullOrEmpty(uname))
{
SqlCommand cmd = new SqlCommand("select * from users WHERE ucode=#ucode", conn);
SqlDataAdapter dadapter = new SqlDataAdapter();
conn.Open();
txtUserName.ReadOnly = false;
txtUserShortName.ReadOnly = false;
txtPassword.ReadOnly = false;
dadapter.SelectCommand = cmd;
cmd.Parameters.Add(new SqlParameter("#ucode", ucode));
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
LblUcode.Text = dr["ucode"].ToString();
txtPassword.Text=dr["pswd"].ToString();
txtUserShortName.Text = dr["ushortname"].ToString();
txtUserName.Text = dr["uname"].ToString();
}
dr.Close();
conn.Close();
}
}
SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE", conn);
cmd.Parameters.AddWithValue("#Uname", txtUserName.Text);
cmd.Parameters.AddWithValue("#Ushortname", txtUserShortName.Text);
cmd.Parameters.AddWithValue("#Pswd", txtPassword.Text);
cmd.Parameters.AddWithValue("#UCODE", LblUcode.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
There is no error, the data simply isn't being updated.
You need to make sure the parameter names match exactly what they do in your sql string.
cmd.Parameters.AddWithValue("#UCODE", UCODE);
Also, either wrap all of that in a using or try/finally to dispose of the connection. I'm assuming you've already got code to open the connection before trying to execute it.
Try this:-
using(SqlConnection conn = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE ", conn))
{
cmd.Parameters.AddWithValue("#Uname", txtUserName.Text);
cmd.Parameters.AddWithValue("#Ushortname", txtUserShortName.Text);
cmd.Parameters.AddWithValue("#Pswd", txtPassword.Text);
cmd.Parameters.AddWithValue("#UCODE", UCODE);
conn.Open();
cmd.ExecuteNonQuery();
}
}
You are missing # in Ucode. Also, its a good practice to wrap your code inside using block check this.
See the edited below code:-
if (!PostBack)
{
string databaseconnectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
string sql = "update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE";
using (SqlConnection conn = new SqlConnection(databaseconnectionstring))
{
conn.Open();
using (SqlCommand cmd= new SqlCommand())
{
cmd.CommandText=sql;
cmd.Connection=databaseconnectionstring;
cmd.Parameters.AddWithValue("#Uname",txtUserName.Text );
cmd.Parameters.AddWithValue("#Ushortname",txtUserShortName.Text );
cmd.Parameters.AddWithValue("#Pswd",txtPassword.Text );
cmd.Parameters.AddWithValue("#UCODE", UCODE);
cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
string bsname = Request.QueryString["bsname"];
string bscode = Request.QueryString["bscode"];
if (!string.IsNullOrEmpty(bsname))
{
if (string.IsNullOrEmpty(txtBsName.Text))
{
SqlCommand cmd = new SqlCommand("select * from bs WHERE bscode=#bscode", conn);
SqlDataAdapter dadapter = new SqlDataAdapter();
conn.Open();
txtBsName.ReadOnly = false;
dadapter.SelectCommand = cmd;
cmd.Parameters.Add(new SqlParameter("#bscode", bscode));
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lblBsCode.Text = dr["bscode"].ToString();
txtBsName.Text = dr["bsname"].ToString();
}
dr.Close();
conn.Close();
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
conn.Open();
string UCODE = LblUcode.Text;
SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE", conn);
cmd.Parameters.AddWithValue("#Uname",txtUserName.Text );
cmd.Parameters.AddWithValue("#Ushortname",txtUserShortName.Text );
cmd.Parameters.AddWithValue("#Pswd",txtPassword.Text );
cmd.Parameters.AddWithValue("#UCODE", UCODE);
cmd.ExecuteNonQuery();
cmd.Dispose();
ShowMessage("Company Data update Successfully......!");
clear();
}
Thank you all its working now with the help of above code.

I must need to open two connections to execute two different queries?

Currently I am executing two queries against two different tables and getting this exception,
The connection was not closed. The connection's current state is open.
This is what I am trying to do,
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
using (SqlCommand cmd = new SqlCommand(deleteStatement, connection))
{
connection.Open();
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(deleteStatement2, connection))
{
connection.Open();
cmd2.Parameters.Add(new SqlParameter("#userID", userID));
int result2 = cmd2.ExecuteNonQuery();
if (result2 == 1)
{
BindData();
}
}
}
}
I am doing this because Table2 has userID as foreign key and must be deleted before deleting user actually
you are calling Open() twice. You can remove the second call Open().
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
using (SqlCommand cmd = new SqlCommand(deleteStatement, connection))
{
connection.Open();
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(deleteStatement2, connection))
{
// connection.Open(); // remove this line
cmd2.Parameters.Add(new SqlParameter("#userID", userID));
int result2 = cmd2.ExecuteNonQuery();
if (result2 == 1)
{
BindData();
}
}
}
}
The second connection.Open() is not required as it will be open from first statement.
Still to be on the safer side, you can use
if (connection.State == ConnectionState.Closed)
connection.Open();
The second connection.Open(); doesn't need to be there. The first one is enough; as the error message says, it's already open.
One connection can perform multiple queries, with only a single call to Open.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(deleteStatement, connection))
{
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd2 = new SqlCommand(deleteStatement2, connection))
{
cmd2.Parameters.Add(new SqlParameter("#userID", userID));
int result2 = cmd2.ExecuteNonQuery();
if (result2 == 1)
{
BindData();
}
}
}
}
I think this will work:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = deleteStatement;
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
cmd.CommandText = deleteStatement2;
int result = cmd.ExecuteNonQuery();
if (result == 1) BindData();
}
}

Categories

Resources