How to use SQL Data Reader to check quantity in database? - sqldatareader

I want to check quantity in the tblProducts with the quantity selected by the user. If the user selects more than in tblProducts, there will be a pop up message and the quantity will not added. If there is available quantity in tblProducts, the user can add the quantity. Do I need to put SP_UpdateCart in both if statement?
if (e.CommandName == "DoPlus")//Check quantity here
{
string PID = (e.CommandArgument.ToString());
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SP_getUserCartItem", con)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("#PID", PID);
cmd.Parameters.AddWithValue("#UserID", UserID);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
int myQty = Convert.ToInt32(dr["Qty"].ToString());
int PQuantity = Convert.ToInt32(dr["PQuantity"].ToString());
if (dt.Rows.Count > 0)
{
if (myQty < PQuantity)
{
Int32 updateQty = Convert.ToInt32(dt.Rows[0]["Qty"].ToString());
SqlCommand myCmd = new SqlCommand("SP_UpdateCart", con)
{
CommandType = CommandType.StoredProcedure
};
myCmd.Parameters.AddWithValue("#Quantity", updateQty + 1);
myCmd.Parameters.AddWithValue("#CartPID", PID);
myCmd.Parameters.AddWithValue("#UserID", UserID);
con.Open();
Int64 CartID = Convert.ToInt64(myCmd.ExecuteScalar());
con.Close();
BindProductCart();
BindCartNumber();
}
else if (myQty > PQuantity)//check quantity between tblCart and
tblProducts
{
Response.Write("<script>alert('Please choose quantity less than
stated!');</script>");
Int32 updateQty = Convert.ToInt32(dt.Rows[0]["Qty"].ToString());
SqlCommand myCmd = new SqlCommand("SP_UpdateCart", con)
{
CommandType = CommandType.StoredProcedure
};
myCmd.Parameters.AddWithValue("#Quantity", updateQty);
myCmd.Parameters.AddWithValue("#CartPID", PID);
myCmd.Parameters.AddWithValue("#UserID", UserID);
con.Open();
Int64 CartID = Convert.ToInt64(myCmd.ExecuteScalar());
con.Close();
BindProductCart();
BindCartNumber();
}
}
}
dr.Close();
}con.Close();
}
}
}

Related

Stored procedure with input & output parameters and 2 recordsets

I try to extract the results in c# asp.net from my stored procedure but it has 2 recordsets. the first with 1 row and the second with many rows as dates.
The code
public string penth_slqDAYS(string connectionString)
{
string sMonth = DateTime.Now.Month.ToString();
string syear = DateTime.Now.Year.ToString();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command1 = new SqlCommand("penthhmera_proc", connection);
/////////////////////////////
SqlParameter param1;
param1 = command1.Parameters.Add("#prs_nmb_pen", SqlDbType.VarChar, 7);
param1.Value = prs_nmb_lb1.Text.Trim();
SqlParameter param2;
param2 = command1.Parameters.Add("#month_pen", SqlDbType.Int);
param2.Value = sMonth;
SqlParameter param3;
param3 = command1.Parameters.Add("#year_int", SqlDbType.Int);
param3.Value = syear;
/////////////////////////
command1.Parameters.Add("#days_out", SqlDbType.Int);
command1.Parameters["#days_out"].Direction = ParameterDirection.Output;
command1.Parameters.Add("#message_out", SqlDbType.VarChar,50);
command1.Parameters ["#message_out"].Direction = ParameterDirection.Output;
command1.Parameters.Add("#dateess_out", SqlDbType.Date);
command1.Parameters["#dateess_out"].Direction = ParameterDirection.Output;
///////////////////////////
connection.Open();
command1.CommandType = CommandType.StoredProcedure;
command1.ExecuteNonQuery();
days_penthwork_tx.Text = Convert.ToString(command1.Parameters["#days_out"].Value);
message_tx.Text = Convert.ToString(command1.Parameters["#message_out"].Value);
///the above parameter contains rows with dates
Label12.Text = Label12.Text + Convert.ToString(command1.Parameters["#dateess_out"].Value);
connection.Close();//close connection
}
return "success";
}
catch (Exception e)
{
return e.ToString();
}
}
My SQL Server stored procedure:
the results
and the query when c# run the code
declare #p4 int
set #p4 = 3
declare #p5 varchar(50)
set #p5 = 'some text'
declare #p6 date
set #p6 = NULL
exec penthhmera_proc #prs_nmb_pen = '274484',
#month_pen = 1,
#year_int = 2021,
#days_out = #p4 output,
#message_out = #p5 output,
#dateess_out = #p6 output
select #p4, #p5, #p6
I think that with that way #p6 is always null.
Finally I want to load all the values from the second recordset to a Gridview or something like a table in order to show it in my webform.
Any idea?
Thanks in advance
ExecuteReader was the answer. thnx Charlieface.
connection.Open();
command1.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = command1.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//some code
}
dr.NextResult();
while (dr.Read())
{
//some code
}
}
else
{
Console.WriteLine("No data found.");
}

Need algorithm For room reservation

I need a room reservation algorithm that room should not be book before its date once a room is booked should not be book on that similar date. I am using sql server and was using status active or booked but its not working.
public void res(DateTime? arrivalDate,DateTime? departureDate)
{
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = (#"Server=DESKTOP-8JJO9NL\SQLEXPRESS;Database=HMS;Trusted_Connection=True");
myConn.Open();
SqlCommand com = new SqlCommand();
com.Connection = myConn;
string sql = "";
sql = "select count(*) from Roomsdata where Room#=#roomnum and Status='Active and arrivaldate >= #arrivalDate and departure <= #departureDate'";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#roomnum", Roomnum);
com.Parameters.AddWithValue("#arrivalDate", arrivalDate);
com.Parameters.AddWithValue("#departureDate", departureDate);
int numRecords = (int)com.ExecuteScalar();
if (numRecords == 1)
{
SqlConnection myConn2 = new SqlConnection();
myConn2.ConnectionString = (#"Server=DESKTOP-8JJO9NL\SQLEXPRESS;Database=HMS;Trusted_Connection=True");
myConn2.Open();
SqlCommand myCmd = new SqlCommand("update Roomsdata set [customername]=#customername ,[contact] =#contact ,[arrivaldate]=#arrivaldate,[departure]=#departure ,[Status]='Booked' ,[stayingdays]=DATEDIFF(day,arrivaldate,departure) ,[Total amount]=DATEDIFF(day,arrivaldate,departure)*1278 FROM [HMS].[dbo].[Roomsdata] where Room#=#roomnum1", myConn2);
myCmd.Parameters.AddWithValue("roomnum1", Roomnum);
myCmd.Parameters.AddWithValue("#customername", Costumername);
myCmd.Parameters.AddWithValue("#contact", Contact);
myCmd.Parameters.AddWithValue("#arrivaldate", Arrivaldate);
myCmd.Parameters.AddWithValue("#departure", Departuredate);
myCmd.ExecuteNonQuery();
myConn2.Close();
}
else
{
throw new Exception("Room is Already Booked");
}

Insert records in database in which have 3 foreign keys

I'm trying to insert a record in the table but the problem is in that table have 3 foreign keys. I'll be using dataTable for that but it gives an error 'There is no row position at 0'
                             
There is my code:
try
{
using (var sqlConnection = new Helpers.SqlConnectionHelpers())
{
var connection = sqlConnection.OpenConnection();
command = new SqlCommand("CarSold_Insert", connection);
command.CommandType = CommandType.StoredProcedure;
SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = '" + txtPrice.Text + "'", connection);
DataTable table = new DataTable();
DataSet dataSet = new DataSet();
table.Load(commandTwo.ExecuteReader());
var carForSaleId = table.Rows[0]["CarForSaleId"].ToString();
var userId = table.Rows[0]["UserId"].ToString();
var salesPersonId = table.Rows[0]["SalesPersonId"].ToString();
command.Parameters.AddWithValue("CarForSaleId", carForSaleId);
command.Parameters.AddWithValue("UserId", userId);
command.Parameters.AddWithValue("SalesPersonId", salesPersonId);
command.Parameters.AddWithValue("Price", txtPrice.Text);
command.Parameters.AddWithValue("DateSold", dateSold);
command.Parameters.AddWithValue("MonthlyPaymentDate", monthlyPaymentDate);
command.Parameters.AddWithValue("MonthlyPaymentAmount", txtPaymentAmount.Text);
//connection.Open();
int k = command.ExecuteNonQuery();
command.Parameters.Clear();
if (k != 0)
{
Response.Redirect("~/AdminPanel/CarSold.aspx");
}
else
{
lblAns.Text = "Record Not Inserted into the database";
lblAns.ForeColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
lblAns.Text = ex.Message;
}
Since Price column is float you need to write query with query parameter like this:
SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = #Price", connection);
commandTwo.Parameters.AddWithValue("#Price", txtPrice.Text);
The above mentioned command will give return you the carForSaleId, userId, salesPersonId which you will use in the insert command

Retrieving multiple rows from stored procedures

My stored procedure proc_search returns only the name on execution and I have been using the following code in ASP.NET to display the value...
SqlCommand cmd = new SqlCommand("proc_search", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#branch", SqlDbType.VarChar).Value = branchidtext.Text;
cmd.Parameters.Add("#Acct", SqlDbType.VarChar).Value = accountidtext.Text;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
nametext.Text = reader[0].ToString();
}
If I have a procedure which returns multiple columns and multiple rows like Name, Address, Age... How do I display it in the text boxes? Please help.
If you know exact order of data you can say
while (reader.Read())
{
nametext.Text = reader[0].ToString();
agetext.Text = reader[1].ToString();
addresstext.Text = reader[2].ToString();
}
etc... If you don't know the ordering than say
while (reader.Read())
{
nametext.Text = reader["Name"].ToString();
agetext.Text = reader["Age"].ToString();
addresstext.Text = reader["Address"].ToString();
}
Use this kind of method. This will retun dataset having multiple rows and cols
public DataSet GetDataSet()
{
SqlConnection conn = new SqlConnection(con);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "proc_search";
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
return ds;
}

How do I pass a querystring value into a select statement in ASP.NET?

How do I pass a querystring value into a select statement in ASP.NET?
Here's what I've tried:
{
string myID = (Request.QueryString["ID"] ?? "0").ToString();
SqlConnection con = new SqlConnection
(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT ID, Name, Date, Description FROM MyTable
where ID=#ID", con);
DataTable dt = new DataTable();
da.Fill(dt);
GV_InlineEditing.DataSource = dt;
GV_InlineEditing.DataBind();
}
Use a SqlCommand and add the parameter to it:
string query = "SELECT ID, Name, Date, Description FROM MyTable where ID=#ID";
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID", myID);
var da = new SqlDataAdapter(cmd);

Resources