Fetching Data from database as per details - asp.net

string date = ddlShowDates.SelectedValue.ToString();
cmd = new SqlCommand("SELECT tbl_Shows.ShowTime FROM tbl_Shows INNER JOIN tbl_MovieTimings ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId WHERE tbl_MovieTimings.Date='" + date + "'", con);
I want to display show time in dropdownlist as per date is selected.

Always use sql-parameters instead of string concatenation to prevent sql-injection.
I guess you have a second DropDownList which should be filled from the first:
DateTime date = DateTime.Parse(ddlShowDates.SelectedValue);
string sql = #"SELECT tbl_Shows.ShowTime
FROM tbl_Shows
INNER JOIN tbl_MovieTimings
ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId
WHERE tbl_MovieTimings.Date=#Date";
using(var con = new SqlConnection("ConnectionString"))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#Date", SqlDbType.Date).Value = date;
con.Open();
using(var rd = cmd.ExecuteReader())
{
while(rd.Read())
{
TimeSpan time = rd.GetTimeSpan(0);
timeDropDownList.Items.Add(time.ToString());// change format as desired in TimeSpan.ToString
}
}
}

Related

How to store a select query result ( one result ) to a variable using executescalar() ? ( ASP.NET )

i have to store a select query result in a variable .i'm new in asp.net . i used executescalar but it doesn't work. i try many times but i failed here my last try :
using (SqlConnection sqlConnection = new SqlConnection())
{
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
sqlConnection.ConnectionString = connetionString;
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, sqlConnection);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
string result = dataset.Tables[0].ToString();
}
Can you fix the code to me? i have to store the result in a variable
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
string result = null;
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
result = cmd.ExecuteScalar().ToString();
}

Select Values in From SQLServer & Show in The Labels in ASP

i want to Select Values ex(Date,Time....)from SQLServer on the PageLoad & shows Them in The Many Labels. i try this code but in all labels shows the Time . i want to show All Values not one value in all labels . Please help me .
string strquery = "select Time,Date,SeatPrice,EventName from Event_SingleReservation";
SqlConnection connection2 = DBConnection.getConnection();
connection2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection2;
cmd2.CommandText = strquery;
string eventname = cmd2.ExecuteScalar().ToString();
lbl1_EventName.Text = eventname;
string eventdate = cmd2.ExecuteScalar().ToString();
lbl2_EventDate.Text = eventdate;
string eventtime = cmd2.ExecuteScalar().ToString();
lbl3_EventTime.Text = eventtime;
string seatprice = cmd2.ExecuteScalar().ToString();
lbl_seatpriceshow.Text = seatprice;
The ExecuteScalar() selects only one value from the first column - i.e. using it against select Time,Date,SeatPrice,EventName from Event_SingleReservation will return only Time which is the first column.
To select all values you should use ExecuteReader()
SqlDataReader reader = cmd2.ExecuteReader();
if (reader.Read())
{
lbl1_EventName.Text = reader[0];
lbl3_EventDate.Text = reader[1];
...
}
See What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

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);

Populating a drop down list dynamically in ASP.net, and passing that value to another query?

2 questions for everybody.
1) How can I order the years by their value, it crashes when I use DESC?
2) If I populate my list like so:
string strConn = ConfigurationManager.ConnectionStrings["rde_410978ConnectionString"].ToString();
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales DESC"; //DESC DOESNT WORK?
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
How can I make the year selected appear under ddItems.SelectedItem?
WHERE Year = " + ddItems.SelectedItem + "GROUP BY Name ";
That part of another query doesn't work when I populate my list dynamically, any reasons why/ how can I fix it.
Regards.
EDIT:
To make my second question clearer, after debugging its always selecting the top item in the drop down list not the actual selected item?
First, in your sql you are missing "order by"...use this
"Select Distinct Year from MonthlySales order by Year DESC"
Second, you need to make use of the SelectedValue property to get your dropdown's selected value...as below...
WHERE Year = " + ddItems.SelectedValue + " GROUP BY Name";
Having said that, I strongly recommend you to use..."parameterized" sql...Here is an example on how you could enable parameterized sql query...
Give me parameterized SQL, or give me death
Update:
Looks like you are binding your dropdown on every post back...you may try this...
if (!Page.IsPostBack && objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
Ans 1)
cmd.CommandText = "Select Distinct Year from MonthlySales ORDER BY 1 DESC"
You are missing order by. Here it is.
"Select Distinct Year from MonthlySales order by Year DESC";
For your second part you can do this. Please mind the space in " GROUP BY Name"
WHERE Year = " + ddItems.SelectedItem.Text + " GROUP BY Name ";
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales Order By DESC";
using (DataSet objDs = new DataSet())
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter())
{
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
}
}
}
}

Resources