i have a table with 3 columns(EmpId,EmpName,EmpSalary).
i am using a prepared statement to retrieve all the data from this table using prepared statement.
here is what i have written...
try
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT EmpId,EmpName,EmpSalary FROM EmpDetails";
SqlParameter paraId = new SqlParameter();
paraId.ParameterName = "#id";
paraId.SqlDbType = SqlDbType.Int;
paraId.Size = 32;
SqlParameter paraName = new SqlParameter();
paraName.ParameterName = "#name";
paraName.SqlDbType = SqlDbType.VarChar;
paraName.Size = 50;
SqlParameter paraSal = new SqlParameter();
paraSal.ParameterName = "#sal";
paraSal.SqlDbType = SqlDbType.Decimal;
paraSal.Precision = 7;
paraSal.Scale = 2;
cmd.Parameters.Add(paraId);
cmd.Parameters.Add(paraName);
cmd.Parameters.Add(paraSal);
con.Open();
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
string str = "";
while(dr.Read())
{
string id = dr.GetInt32(0).ToString();
string name = dr.GetString(1);
string sal = dr.IsDBNull(2) ? "is null" : dr.GetDecimal(2).ToString();
str += id + "\t" + name + "\t" + sal + "\n";
}
MessageBox.Show(str);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
but i am getting an error as follows :
"The parameterized Query expects the parameter #id , which was not supplied."
What mistake am i doing here..??
Please use cmd.Parameters.AddWithValue(). Using cmd.Parameters.Add() is deprecated. Google its uses :-)
I checked your code, you will need to supply parameters value like below.
try
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT EmpId,EmpName,EmpSalary FROM EmpDetails ";
SqlParameter paraId = new SqlParameter();
paraId.ParameterName = "#id";
paraId.SqlDbType = SqlDbType.Int;
paraId.Size = 32;
SqlParameter paraName = new SqlParameter();
paraName.ParameterName = "#name";
paraName.SqlDbType = SqlDbType.VarChar;
paraName.Size = 50;
SqlParameter paraSal = new SqlParameter();
paraSal.ParameterName = "#sal";
paraSal.SqlDbType = SqlDbType.Decimal;
paraSal.Precision = 7;
paraSal.Scale = 2;
//i assume you forgot to setup parameter values.
paraId.Value = 1;
paraName.Value = "thisName";
paraSal.Value = 343;
cmd.Parameters.Add(paraId);
cmd.Parameters.Add(paraName);
cmd.Parameters.Add(paraSal);
con.Open();
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
string str = "";
while (dr.Read())
{
string id = dr.GetInt32(0).ToString();
string name = dr.GetString(1);
string sal = dr.IsDBNull(2) ? "is null" : dr.GetDecimal(2).ToString();
str += id + "\t" + name + "\t" + sal + "\n";
}
MessageBox.Show(str);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
Related
So i am quite new to programing overall but i am learning pretty quick, so what im stuck on right now is that i need to read from a SQL table but i only want to read a single row by a key inside of the database.
The code i have down here does the work but i am quite sure you can do this alot more smooth as this is not very clean.
How could i do this in another more simple way?
What i want for result is to add all rows in to their own strings so that i can more easy use them for labels and other information in my program.
private static MySqlConnection dbConn;
static string MySQLConnectionString = "Server='ip';Port='port';Database='name';User='user';Password='Password';SslMode='none'";
public static void InitializeDB()
{
dbConn = new MySqlConnection(MySQLConnectionString);
string commandSuperuser = "SELECT * FROM sl WHERE User=(1)";
string commandUserOne = "SELECT * FROM sl WHERE User=(1)";
string commandUserTwo = "SELECT * FROM sl WHERE User=(2)";
string commandUserThree = "SELECT * FROM sl WHERE User=(3)";
string commandUserFour = "SELECT * FROM sl WHERE User=(4)";
string commandUserFive = "SELECT * FROM sl WHERE User=(5)";
string commandUserSix = "SELECT * FROM sl WHERE User=(6)";
string commandUserSeven = "SELECT * FROM sl WHERE User=(7)";
string commandUserEight = "SELECT * FROM sl WHERE User=(8)";
MySqlCommand cmd1 = new MySqlCommand(commandSuperuser, dbConn);
dbConn.Open();
MySqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
UserSuperuserName = reader1["Name"].ToString() + " " + reader1["Lastname"].ToString();
UserSuperuserENumber = reader1["ENumber"].ToString();
UserSuperuserNumber = reader1["Number"].ToString();
UserSuperuserNickname = reader1["Nickname"].ToString();
UserSuperuserMail = reader1["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd2 = new MySqlCommand(commandUserOne, dbConn);
dbConn.Open();
MySqlDataReader reader2 = cmd2.ExecuteReader();
while (reader2.Read())
{
UserOneName = reader2["Name"].ToString() + " " + reader2["Lastname"].ToString();
UserOneENumber = reader2["ENumber"].ToString();
UserOneNumber = reader2["Number"].ToString();
UserOneNickname = reader2["Nickname"].ToString();
UserOneMail = reader2["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd3 = new MySqlCommand(commandUserTwo, dbConn);
dbConn.Open();
MySqlDataReader reader3 = cmd3.ExecuteReader();
while (reader3.Read())
{
UserTwoName = reader3["Name"].ToString() + " " + reader3["Lastname"].ToString();
UserTwoENumber = reader3["ENumber"].ToString();
UserTwoNumber = reader3["Number"].ToString();
UserTwoNickname = reader3["Nickname"].ToString();
UserTwoMail = reader3["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd4 = new MySqlCommand(commandUserThree, dbConn);
dbConn.Open();
MySqlDataReader reader4 = cmd4.ExecuteReader();
while (reader4.Read())
{
UserThreeName = reader4["Name"].ToString() + " " + reader4["Lastname"].ToString();
UserThreeENumber = reader4["ENumber"].ToString();
UserThreeNumber = reader4["Number"].ToString();
UserThreeNickname = reader4["Nickname"].ToString();
UserThreeMail = reader4["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd5 = new MySqlCommand(commandUserFour, dbConn);
dbConn.Open();
MySqlDataReader reader5 = cmd5.ExecuteReader();
while (reader5.Read())
{
UserFourName = reader5["Name"].ToString() + " " + reader5["Lastname"].ToString();
UserFourENumber = reader5["ENumber"].ToString();
UserFourNumber = reader5["Number"].ToString();
UserFourNickname = reader5["Nickname"].ToString();
UserFourMail = reader5["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd6 = new MySqlCommand(commandUserFive, dbConn);
dbConn.Open();
MySqlDataReader reader6 = cmd6.ExecuteReader();
while (reader6.Read())
{
UserFiveName = reader6["Name"].ToString() + " " + reader6["Lastname"].ToString();
UserFiveENumber = reader6["ENumber"].ToString();
UserFiveNumber = reader6["Number"].ToString();
UserFiveNickname = reader6["Nickname"].ToString();
UserFiveMail = reader6["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd7 = new MySqlCommand(commandUserSix, dbConn);
dbConn.Open();
MySqlDataReader reader7 = cmd7.ExecuteReader();
while (reader7.Read())
{
UserSixName = reader7["Name"].ToString() + " " + reader7["Lastname"].ToString();
UserSixENumber = reader7["ENumber"].ToString();
UserSixNumber = reader7["Number"].ToString();
UserSixNickname = reader7["Nickname"].ToString();
UserSixMail = reader7["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd8 = new MySqlCommand(commandUserSeven, dbConn);
dbConn.Open();
MySqlDataReader reader8 = cmd8.ExecuteReader();
while (reader8.Read())
{
UserSevenName = reader8["Name"].ToString() + " " + reader8["Lastname"].ToString();
UserSevenENumber = reader8["ENumber"].ToString();
UserSevenNumber = reader8["Number"].ToString();
UserSevenNickname = reader8["Nickname"].ToString();
UserSevenMail = reader8["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd9 = new MySqlCommand(commandUserEight, dbConn);
dbConn.Open();
MySqlDataReader reader9 = cmd9.ExecuteReader();
while (reader9.Read())
{
UserEightName = reader9["Name"].ToString() + " " + reader9["Lastname"].ToString();
UserEightENumber = reader9["ENumber"].ToString();
UserEightNumber = reader9["Number"].ToString();
UserEightNickname = reader9["Nickname"].ToString();
UserEightMail = reader9["Email"].ToString();
}
dbConn.Close();
}
If someone has any tips/examples that would be awesome.
You could use MysqlDataAdapter and DataTable and save the values to String arrays.
public static void InitializeDB()
{
dbConn = new MySqlConnection(MySQLConnectionString);
dbConn.Open();
try
{
using (MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM S1", dbConn))
{
DataTable dt = new DataTable();
da.Fill(dt);
int a = 0;
if (dt.Rows.Count > 0)
{
string[] UserName = new string[dt.Rows.Count];
string[] UserENumber = new string[dt.Rows.Count];
string[] UserNumber = new string[dt.Rows.Count];
string[] UserNickname = new string[dt.Rows.Count];
string[] UserMail = new string[dt.Rows.Count];
for (a = 0; a < dt.Rows.Count; a++)
{
UserName[a] = dt.Rows[a]["Name"].ToString();
UserENumber[a] = dt.Rows[a]["Enumber"].ToString();
UserNumber[a] = dt.Rows[a]["Number"].ToString();
UserNickname[a] = dt.Rows[a]["Nickname"].ToString();
UserMail[a] = dt.Rows[a]["Mail"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dbConn.Close();
}
}
I have a get details form, and I know that using try and catch as a way of validation here is bad practice. How would I check to see if the CustID exists and then tell the user that what they entered does not exist?
Apologies if this is a silly question and it's obvious and..., I'm a beginner.
public void getdetails()
{
lblMessage.Text = "";
if (txtCID.Text == "")
{
lblMessage.Text = "Please enter a Customer ID before obtaining details.";
}
else
{
command.Connection.Open();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustomer";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = txtCID.Text;
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
txtFName.Text = table.Rows[0].Field<string>("FirstName");
txtFName.DataBind();
txtLName.Text = table.Rows[0].Field<string>("Surname");
txtLName.DataBind();
rdoGender.Text = table.Rows[0].Field<string>("Gender").ToString();
txtAge.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAdd1.Text = table.Rows[0].Field<string>("Address1").ToString();
txtAge.DataBind();
txtAdd2.Text = table.Rows[0].Field<string>("Address2").ToString();
txtAge.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City").ToString();
txtAge.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone").ToString();
txtAge.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile").ToString();
txtAge.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email").ToString();
txtEmail.DataBind();
command.Connection.Close();
}
}
Since you fill a DataTable it's easy to determine if the customer existed, use DataTable.Rows.Count > 0:
bool customerExists = table.Rows.Count > 0;
if(!customerExists)
{
lblMessage.Text = $"The customer with CustomerID={txtCID.Text} is unknown.";
}
Apart from that...
Use the using-statement for your connection and everything that implements IDisposable
convert the string to int with C#, don't let the database do it for you. On that way, using int.TryParse, you also validate the input
So here is your method including these and other improvements:
public void LoadCustomerDetails()
{
lblMessage.Text = "";
if (String.IsNullOrWhiteSpace(txtCID.Text))
{
lblMessage.Text = "Please enter a CustomerID before obtaining details.";
return;
}
DataTable table = new DataTable();
int customerID;
using (var conn = new SqlConnection(Properties.Settings.Default.TestDbCon))
using (var da = new SqlDataAdapter("GetCustomer", conn))
using (var cmd = da.SelectCommand)
{
cmd.CommandType = CommandType.StoredProcedure;
if (!int.TryParse(txtCID.Text.Trim(), out customerID))
{
lblMessage.Text = "Please enter a valid integer CustomerID before obtaining details.";
return;
}
cmd.Parameters.Add("#CustID", SqlDbType.Int).Value = customerID;
da.Fill(table); // you don't need to open/close the connection with Fill
}
if (table.Rows.Count == 0)
{
lblMessage.Text = $"No customer with CustomerID={customerID} found.";
return;
}
DataRow custumerRow = table.Rows.Cast<DataRow>().Single(); // to cause an exception on multiple customers with this ID
txtFName.Text = custumerRow.Field<string>("FirstName");
txtLName.Text = custumerRow.Field<string>("Surname");
rdoGender.Text = custumerRow.Field<string>("Gender").ToString();
txtAge.Text = custumerRow.Field<int>("Age").ToString();
txtAdd1.Text = custumerRow.Field<string>("Address1").ToString();
txtAdd2.Text = custumerRow.Field<string>("Address2").ToString();
txtCity.Text = custumerRow.Field<string>("City").ToString();
txtPhone.Text = custumerRow.Field<string>("Phone").ToString();
txtMobile.Text = custumerRow.Field<string>("Mobile").ToString();
txtEmail.Text = custumerRow.Field<string>("Email").ToString();
}
I'm not sure I fully understood your question. What I would do is:
public bool getdetails()
{
bool found = false;
int id;
bool isnumber;
lblMessage.Text = "";
isnumber = int.TryParse(txtCID.Text, out id);
if (!isnumber)
{
lblMessage.Text = "Please enter a valid Customer ID before obtaining details.";
}
else
{
command.Connection.Open();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustomer";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = id;
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
txtFName.Text = table.Rows[0].Field<string>("FirstName");
txtFName.DataBind();
txtLName.Text = table.Rows[0].Field<string>("Surname");
txtLName.DataBind();
rdoGender.Text = table.Rows[0].Field<string>("Gender").ToString();
txtAge.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAdd1.Text = table.Rows[0].Field<string>("Address1").ToString();
txtAge.DataBind();
txtAdd2.Text = table.Rows[0].Field<string>("Address2").ToString();
txtAge.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City").ToString();
txtAge.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone").ToString();
txtAge.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile").ToString();
txtAge.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email").ToString();
txtEmail.DataBind();
found = true;
}
else
{
lblMessage.Text = "User with ID " + id + " does not exists";
}
command.Connection.Close();
}
return found;
}
The function will return false if either the id is not specified or does not exist. Another problem is that you don't check if txtCID.Text contains a valid number: in this case a SQL error is would thrown!
I added a number conversion check that ensures that at least the stored procedure execution runs without errors. Anyway, you should wrap the whole procedure in a try-catch to intercept any unpredictable error (db offline or internal db error, etc).
Then, I use table.Rows.Count to verify if the stored procedure returned a result.
Mario.
i have the following code that call a stored procedure and then makes One insert on another table.
The problem is that when the procedure takes few time to complete everything works well, instead,
when the procedure get long time (the session dose not seem to expire ) but the next operaion on the db
makes the session "inactive"
web.config:
</webServices>
<trust level="Full" />
<httpRuntime
executionTimeout="90000000"
maxRequestLength="2097151"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="1000"
enableVersionHeader="true"
/>
asp.net page:
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = connection;
objCmd.CommandText = "insertReqSched";
objCmd.CommandType = CommandType.StoredProcedure;
if((Session["chkAllSoc"] != null)&&(Session["chkAllSoc"].ToString() == "1"))
{
/*
selezionare tutte le soc di vendita e metterli in una string separati da ,
*/
OracleCommand cmd = new OracleCommand("select uidaccount FROM ACCOUNT A INNER JOIN ACCOUNTTYPE AT ON A.UIDACCOUNTTYPE = AT.UIDACCOUNTTYPE WHERE ACCOUNTTYPENAME IN ('RETAILER','ELIGIBLE_CLIENT') order by name asc",connection);
reader = cmd.ExecuteReader();
string socVends = "";
while (reader.Read())
{
socVends = socVends + "" + reader.GetInt32(0) + ",";
}
reader.Close();
OracleParameter socVal = new OracleParameter("socVend",OracleType.VarChar);
socVal.Direction = ParameterDirection.Input;
socVal.Value= socVends.Remove(socVends.Length - 1);
objCmd.Parameters.Add(socVal);
}
else{
OracleParameter socVal = new OracleParameter("socVend",OracleType.VarChar);
socVal.Direction = ParameterDirection.Input;
socVal.Value= ((Session["socVend"] != null) && (Session["socVend"].ToString().Length != 0)) ? Session["socVend"].ToString() : (object)System.DBNull.Value;
objCmd.Parameters.Add(socVal);
}
if((Session["chkAllPlant"]!= null)&&(Session["chkAllPlant"].ToString() == "1"))
{
/*
selezionare tutti gli impianti e metterli in una stringa separati da ,
*/
OracleCommand cmd = new OracleCommand("select plantcode from plant",connection);
reader = cmd.ExecuteReader();
string plants = "";
while (reader.Read())
{
plants = plants + reader.GetString(0) + "," ;
}
reader.Close();
OracleParameter plantCode = new OracleParameter("plantCode",OracleType.VarChar);
plantCode.Direction = ParameterDirection.Input;
plantCode.Value= plants.Remove(plants.Length - 1);
objCmd.Parameters.Add(plantCode);
}
else{
OracleParameter plantCode = new OracleParameter("plantCode",OracleType.VarChar);
plantCode.Direction = ParameterDirection.Input;
plantCode.Value= ((Session["plantcode"] != null) && (Session["plantcode"].ToString().Length != 0)) ? Session["plantcode"].ToString() : (object)System.DBNull.Value;
objCmd.Parameters.Add(plantCode);
}
OracleParameter bllingParam = new OracleParameter("billingcy",OracleType.VarChar);
bllingParam.Direction = ParameterDirection.Input;
bllingParam.Value= ((Session["billingcycle"] != null )&&(Session["billingcycle"].ToString().Length != 0)) ? Session["billingcycle"].ToString() : (object)System.DBNull.Value;
objCmd.Parameters.Add(bllingParam);
OracleParameter freqLet = new OracleParameter("freqLettura",OracleType.VarChar);
freqLet.Direction = ParameterDirection.Input;
freqLet.Value= ((Session["freqLett"] != null )&&(Session["freqLett"].ToString().Length != 0)) ? Session["freqLett"].ToString() : (object)System.DBNull.Value;
objCmd.Parameters.Add(freqLet);
OracleParameter tipoElab = new OracleParameter("tipoElab",OracleType.VarChar);
tipoElab.Direction = ParameterDirection.Input;
tipoElab.Value= ((Session["tipoelab"] != null )&&(Session["tipoelab"].ToString().Length != 0)) ? Session["tipoelab"].ToString() : (object)System.DBNull.Value;
objCmd.Parameters.Add(tipoElab);
OracleParameter startT = new OracleParameter("startTime",OracleType.DateTime);
startT.Direction = ParameterDirection.Input;
startT.Value=Session["fStartDate"].ToString();
objCmd.Parameters.Add(startT);
OracleParameter stopT = new OracleParameter("stopTime",OracleType.DateTime);
stopT.Direction = ParameterDirection.Input;
stopT.Value=Session["fEndDate"].ToString();
objCmd.Parameters.Add(stopT);
OracleParameter schedPara = new OracleParameter("schedDate",OracleType.DateTime);
schedPara.Direction = ParameterDirection.Input;
schedPara.Value=Session["fSCHEDDATE"].ToString();
objCmd.Parameters.Add(schedPara);
OracleParameter seqVal = new OracleParameter("valoreSequence",OracleType.Number);
seqVal.Direction = ParameterDirection.Input;
seqVal.Value = Convert.ToInt32(sequenceVal);
objCmd.Parameters.Add(seqVal);
objCmd.ExecuteNonQuery();
OracleCommand cmdInsert = new OracleCommand("INSERT INTO batchrequest(uidbatchrequest,processnum,scheddate,starttime,stoptime,ratecode) " +
" VALUES (:1,:2,:3,:4,:5,:6)", connection);
cmdInsert.Parameters.Add("1", OracleType.Number).Value = Convert.ToInt32(sequenceVal);
cmdInsert.Parameters.Add("2", OracleType.Number).Value = Convert.ToInt32(Session["selectProcess"]);
cmdInsert.Parameters.Add("3", OracleType.DateTime).Value = date1;
cmdInsert.Parameters.Add("4", OracleType.DateTime).Value = date2;
cmdInsert.Parameters.Add("5", OracleType.DateTime).Value = date3;
cmdInsert.Parameters.Add("6", OracleType.VarChar, 64).Value = Session["tipoelab"].ToString();
try
{
cmdInsert.ExecuteNonQuery();
Label1.Text = "Richiesta inserita correttamente";
connection.Close();
return;
}
catch(Exception ex){
OracleCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update batchrequest set scheddate = :1, starttime = :2, stoptime = :3, ratecode = 'S' where scheddate = :keyValue";
cmd.Parameters.Add("1", OracleType.DateTime).Value = date1;
cmd.Parameters.Add("2", OracleType.DateTime).Value = date2;
cmd.Parameters.Add("3", OracleType.DateTime).Value = date3;
cmd.Parameters.Add("keyValue", OracleType.DateTime).Value = date1;
try
{
cmd.ExecuteNonQuery();
connection.Close();
}
catch(Exception ee){
Label1.Text = "Richiesta inserita correttamente";
return;
}
Label1.Text = "Richiesta inserita correttamente";
return;
}
}
i want highlight that when the procedure takes few time everything works well.
When takes long time last command : Insert or Update never stops on the db and i see the session in
Inactive mode.
If the query takes long, more then HTTP timeout that is set, you might be better off creating a database job, and starting the job from ASP.NET without waiting for it to finish.
This error will come in my code Procedure or function 'gridalldata' expects parameter '#order_no', which wast not supplied. I am sending parameter to procedure like below
try
{
con.Open();
SqlCommand cmd = new SqlCommand("gridalldata", con);
cmd.Parameters.Add("#order_no", SqlDbType.NVarChar).Value = txt_orderno.Text;
SqlDataReader dr = cmd.ExecuteReader();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dr.HasRows)
{
dr.Read();
dataGridView1.Rows[i].Cells[0].Value = dr[0].ToString();
dataGridView1.Rows[i].Cells[2].Value = dr[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = dr[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = dr[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = dr[5].ToString();
dataGridView1.Rows[i].Cells[6].Value = dr[6].ToString();
dataGridView1.Rows[i].Cells[7].Value = dr[7].ToString();
dataGridView1.Rows[i].Cells[8].Value = dr[8].ToString();
dataGridView1.Rows[i].Cells[9].Value = dr[9].ToString();
dataGridView1.Rows[i].Cells[10].Value = dr[13].ToString();
dataGridView1.Rows[i].Cells[11].Value = dr[12].ToString();
}
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
How To Fix This
Use cmd.CommandType = CommandType.StoredProcedure; to execute stored procedure.
Try This:
Try
{
con.Open();
string order= txt_orderno.Text;
SqlCommand cmd = new SqlCommand("gridalldata", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#order_no", SqlDbType.NVarChar).Value=order;
SqlDataReader dr = cmd.ExecuteReader();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dr.HasRows)
{
dr.Read();
dataGridView1.Rows[i].Cells[0].Value = dr[0].ToString();
dataGridView1.Rows[i].Cells[2].Value = dr[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = dr[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = dr[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = dr[5].ToString();
dataGridView1.Rows[i].Cells[6].Value = dr[6].ToString();
dataGridView1.Rows[i].Cells[7].Value = dr[7].ToString();
dataGridView1.Rows[i].Cells[8].Value = dr[8].ToString();
dataGridView1.Rows[i].Cells[9].Value = dr[9].ToString();
dataGridView1.Rows[i].Cells[10].Value = dr[13].ToString();
dataGridView1.Rows[i].Cells[11].Value = dr[12].ToString();
}
}
dr.Close();
con.Close();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
String orderNo=txt_orderno.Text;
// Am assuming gridalldata is your SP
SqlCommand cmd= new SqlCommand(gridalldata, connection);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#order_no", orderNo);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// Code
}
}
The using statement makes sure the connection is closed after use
Also You should bind Your Datagridview like this
Public DataTable FillDataGrid(string orderID)
{
SqlCommand cmd = new SqlCommand("gridalldata", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#order_no", orderNo);
SqlDataAdapter dap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);
return ds.Tables[0];
}
Datatable dt=FillDataGrid(txt_orderno.Text);
DataGridVIew1.DataSource=dt;
How do I pass a stored procedure along with parameters as a string to a function?
I tried this code but no luck..
This is the Business Access Layer code
try
{
string Query_string = "SP_InsertOffer_Tab #offer_name ='" + this.offer_name +"', #offer_price = " + this.offer_price + ",#start_date = '" + this.start_date +
"',#end_date = '" + this.end_date + "'";
int result = DbAcess.Insert_Query(Query_string);
return result;
}
catch (Exception ex)
{
throw ex;
}
finally
{
DbAcess = null;
}
Database layer code is as follows
public int Insert_Query(string strSQL)
{
SqlConnection con = new SqlConnection();
con = OpenConnection();
try
{
sqlcmd = new SqlCommand();
sqlcmd.Connection = con;
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = strSQL;
int Result = sqlcmd.ExecuteNonQuery();
return Result;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
Instead of passing strSQL as the CommandText, where strSQL is the string you create in the first code block (I think...), just pass the SP name as the CommandText and then add Parameters to your sqlcmd object.
SqlParameter p = new SqlParameter("#ParameterName", parametervalue));
sqlcmd.Parameters.Add(p);
Just to try to RESOLVE your problem, but BEWARE that this method is very dangerous and NOT RECOMMENDED for the Sql Injection problem.
string Query_string = "EXEC SP_InsertOffer_Tab #offer_name ='" +
this.offer_name +"', #offer_price = " +
this.offer_price + ",#start_date = '" +
this.start_date + "',#end_date = '" + this.end_date + "'";
and change the CommandType to Text.
A better approach would be to change the Insert_Query method
public int Insert_Query(string strSQL, SqlParameter[] prm)
{
using(SqlConnection con = OpenConnection())
{
sqlcmd = new SqlCommand(strSql, con);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddRange(prm)
int Result = sqlcmd.ExecuteNonQuery();
return Result;
}
}
then call it in this way
SqlParameter[] prms = new SqlParameter[]
{
new SqlParameter("#offer_name", SqlDbType.NVarChar),
new SqlParameter("#offer_price", SqlDbType.Money),
new SqlParameter("#start_date", SqlDbType.SmallDateTime),
new SqlParameter("#end_date", SqlDbType.SmallDateTime)
};
prms[0].Value = this.offer_name;
prms[1].Value = this.offer_price;
prms[2].Value = this.start_date;
prms[3].Value = this.end_date;
int result = DbAcess.Insert_Query(Query_string, prms);