Passing DropDownList value into SQL command in ASP.net - sql

I have a DropDownList which gets it values from SQL table
I want to get the Average of the selected item (course in this case) from the dropDownList and to show it in a label :
This section works -
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand("SELECT Course FROM GradesTable1", sqlConnection1);
Command.Connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(Command);
DataTable dataTble1 = new DataTable();
dataAdapter.Fill(dataTble1);
if (dataTble1.Rows.Count > 0)
{
foreach (DataRow row in dataTble1.Rows)
{
ListItem course1 = new ListItem(row["Course"].ToString());
if (!DropDownList1.Items.Contains(course1))
{
DropDownList1.Items.Add(course1); // showing the 2 courses
}
}
}
Command.Connection.Close();
}
}
Here is the problem - (I get nothing, no data )
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand($"SELECT AVG(Grade) FROM GradesTable1 WHERE Course = #course", sqlConnection1);
Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem);
Command.Connection.Open();
SqlDataReader sqlDataReader1 = Command.ExecuteReader();
if (sqlDataReader1.Read())
{
LabelAverage.Text = sqlDataReader1[0].ToString();
}
else
{
LabelAverage.Text = "No Data"; // doesn't get into here anyhow
}
}
EDIT
I tried several variations as $"SELECT AVG(Grade) AS "ClassAVG" FROM GradesTable1 WHERE Course = #course" and Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem.Text), or DropDownList1.SelectedValue
I believe the problem is with the DropDownlist values which being received from the SQL and are not hard coded.
Is there a correct way to this? is it possible without knowing what are the "Courses" in advanced?
Thanks for the answers, feel free to give your opinion.

I found out what was missing in the DropDownList in aspx page (not the aspx.cs page) -the AutoPostBack="true"
Adding that to DropDownList solved the problem.

// query = Sql query
query.Select(s => new MusteriNoktaComboItemDTO
{
Label = s.Adi,
Value = s.ID.ToString()
}).ToList();

Related

ADO.net Performing Multiple queries (ExecuteQuery & ExecuteScalar) and displaying the result in a web form control

Hey wish you all to have a happy holiday,
I am trying to display multiple query results from a SQL database table to a grid view control and a label. I have no problem with the grid view result, but the result from the ExecuteScalar command is not displaying inside my lable control with an ID="myCount". I could not figure out what went wrong with my code. I need your help.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MBSDB"].ConnectionString);
try {
conn.Open();
string query="SELECT * FROM tblBook";
using (SqlCommand mycmd = new SqlCommand(query, conn)) {
myGrid.DataSource = mycmd.ExecuteReader();
myGrid.DataBind();
}
string query2 = "SELECT count(title) FROM tblBook";
using (SqlCommand mycmd2 = new SqlCommand(query2, conn)) {
int count = (int)mycmd2.ExecuteScalar();
myCount.Text = count.ToString();
}
}
catch {
Exception(e);
}
finally { conn.Close(); }
}
Are you sure about there is no error. I think, the error occured and handling in the catch block and you are unaware of it.
You should change it;
(int)mycmd2.ExecuteScalar();
to
Convert.ToInt32(mycmd2.ExecuteScalar());
You can't unboxing an object like this; (int)mycmd2.ExecuteScalar()

ASP.NET 5 - DataSet, DataTable and friends

I'm creating a new webservice in ASP.NET 5 using the new .NET Core library, so far I've only hit an issue with using DataSet and DataTable.
According to this site they are not included at this moment in time, which is fine, but I don't know what alternatives I have at this time, so I'm just looking for some guidance.
I have the following code:
public string Get(string p_sUserId, string p_sUserPassword, int p_iCustId)
{
Select qrySelect = new Select();
using (SqlConnection conn = new SqlConnection(Startup.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(qrySelect.getData(), conn))
{
cmd.Parameters.AddWithValue("#Id", sTestId);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataSet ds = new DataSet())
{
// foo
// bar
}
}
}
}
return "value";
}
How should I handle the data that is being return from the query? I need to build and return a string using the above data fetched from the query. Any help and guidance would be appreciated.
I believe SqlDataReader should work.
string sql = "SELECT * FROM Table";
using (SqlConnection con = new SqlConnection(Startup.ConnectionString)) {
con.Open();
using (SqlCommand command = new SqlCommand(sql, con)) {
using (IDataReader dr = command.ExecuteReader()) {
while (dr.Read()) {
//process data
}
}
}
}
DataTable and SqlDBAdapter are now supported using .NET Standard 2.0. Upgrade to VS2017 Preview, add System.Data.Common and System.Data.SqlClient nugets, and the code below should work. More detail at the blog post here -> https://blogs.msdn.microsoft.com/devfish/2017/05/15/exploring-datatable-and-sqldbadapter-in-asp-net-core-2-0/ . GitHub repo here -> https://github.com/jhealy/aspdotnetcore/tree/master/SqlClientPlay20 .
public static DataTable ExecuteDataTableSqlDA(SqlConnection conn, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
System.Data.DataTable dt = new DataTable();
System.Data.SqlClient.SqlDataAdapter da = new SqlDataAdapter(cmdText, conn);
da.Fill(dt);
return dt;
}

Retrieve SQL Statement Does Not Go Into While Loop

I am having problem when doing retrieve function in 3-tier in C#. Here is the codes:
public DistributionStandardPackingUnits getSPUDetail(string distributionID)
{
DistributionStandardPackingUnits SPUFound = new DistributionStandardPackingUnits();
using (var connection = new SqlConnection(FoodBankDB.connectionString))
{
SqlCommand command = new SqlCommand("SELECT name, description, quantity FROM dbo.DistributionStandardPackingUnits WHERE distribution = '" + distributionID + "'", connection);
connection.Open();
using (var dr = command.ExecuteReader())
{
while (dr.Read())
{
string name = dr["name"].ToString();
string description = dr["description"].ToString();
string quantity = dr["quantity"].ToString();
SPUFound = new DistributionStandardPackingUnits(name, description, quantity);
}
}
}
return SPUFound;
}
When I run in browser, it just won't show up any retrieved data. When I run in debugging mode, I realized that when it hits the while loop, instead of executing the dr.Read(), it simply just skip the entire while loop and return null values. I wonder what problem has caused this. I tested my query using the test query, it returns me something that I wanted so I think the problem does not lies at the Sql statement.
Thanks in advance.
Edited Portion
public static SqlDataReader executeReader(string query)
{
SqlDataReader result = null;
System.Diagnostics.Debug.WriteLine("FoodBankDB executeReader: " + query);
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
result = command.ExecuteReader();
connection.Close();
return result;
}

Values not updates after update query

I am developing a project in ASP.NET with c# and SQL Server 2005 as back end. It includes a page profile.aspx which displays the information of a user from database. The session variable is used to keep track of the current logged in user.
The profiles table in the database contains a username column and 10 others columns like dept, address, contact, skills, interests etc etc.
I am displaying all these values on profile.aspx. Another page is edit_profile.aspx which comes up when the edit button on profile.aspx is clicked. Here the data is displayed in textboxes, with older entries already displayed, which can be edited, and click the Update button to confirm.
The update query runs fine, there is no error, but the values are not updates in the database tables. What is the possible reason? Solution?
Thank you
protected void Page_Load(object sender, EventArgs e)
{
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlDataAdapter sda = new SqlDataAdapter("select * from profiles where username='" + Session["currentusername"].ToString()+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "profiles");
txt_name.Text = ds.Tables["profiles"].Rows[0][0].ToString();
txt_deptt.Text = ds.Tables["profiles"].Rows[0][1].ToString();
txt_qualificatns.Text = ds.Tables["profiles"].Rows[0][2].ToString();
txt_add.Text = ds.Tables["profiles"].Rows[0][3].ToString();
txt_contacts.Text = ds.Tables["profiles"].Rows[0][4].ToString();
txt_interests.Text = ds.Tables["profiles"].Rows[0][5].ToString();
txt_awards.Text = ds.Tables["profiles"].Rows[0][6].ToString();
txt_website.Text = ds.Tables["profiles"].Rows[0][7].ToString();
txt_skills.Text = ds.Tables["profiles"].Rows[0][8].ToString();
txt_mstatus.Text = ds.Tables["profiles"].Rows[0][9].ToString();
ds.Reset();
}
protected void Button1_Click(object sender, EventArgs e)
{
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlCommand sda = new SqlCommand("update profiles set department='"+txt_deptt.Text+"',qualifications='"+txt_qualificatns.Text+"', address='"+txt_add.Text+"', contacts='"+txt_contacts.Text+"', interests='"+txt_interests.Text+"', awards='"+txt_awards.Text+"', website='"+txt_website.Text+"', skills='"+txt_skills.Text+"', mstatus='"+txt_mstatus.Text+"' where username='" + Session["currentusername"].ToString() + "'", con);
DataSet ds = new DataSet();
try
{
con.Open();
int temp=sda.ExecuteNonQuery();
con.Close();
if (temp >= 1)
{
lbl_message.ForeColor = System.Drawing.Color.Green;
lbl_message.Text = "Profile Updated Successfully!";
}
else
{
lbl_message.ForeColor = System.Drawing.Color.Red;
lbl_message.Text = "Integer less than 1";
}
}
catch
{
lbl_message.ForeColor = System.Drawing.Color.Red;
lbl_message.Text = "Try Again Later, An Error Occured!";
}
//Response.Redirect("profile.aspx");
}
}
You are overwriting the contents of your textboxes every time the page loads so the user inputted conntet is never written to the database...
Look at the Page.IsPostBack method. Basically, wrap the commands to fill the textboxes with
if (!Page.IsPostBack) {}
To only load the values into the text box the first time the page loads (and so not overwrite the user entered values when you click the button you need to check that the page isn't a post back.
I think maybe a book on basic ASP.Net will help answer many questions you may have early on.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlDataAdapter sda = new SqlDataAdapter("select * from profiles where username='" + Session["currentusername"].ToString()+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "profiles");
txt_name.Text = ds.Tables["profiles"].Rows[0][0].ToString();
txt_deptt.Text = ds.Tables["profiles"].Rows[0][1].ToString();
txt_qualificatns.Text = ds.Tables["profiles"].Rows[0][2].ToString();
txt_add.Text = ds.Tables["profiles"].Rows[0][3].ToString();
txt_contacts.Text = ds.Tables["profiles"].Rows[0][4].ToString();
txt_interests.Text = ds.Tables["profiles"].Rows[0][5].ToString();
txt_awards.Text = ds.Tables["profiles"].Rows[0][6].ToString();
txt_website.Text = ds.Tables["profiles"].Rows[0][7].ToString();
txt_skills.Text = ds.Tables["profiles"].Rows[0][8].ToString();
txt_mstatus.Text = ds.Tables["profiles"].Rows[0][9].ToString();
ds.Reset();
}
}

silverlight C# code

This is coded in Service.svc.cs file
[OperationContract]
public List<Branch> GetAllBranch()
{
List<Branch> Br = new List<Branch>();
using (SqlConnection con = new SqlConnection(myConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "GetBranch";
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Branch BrName = new Branch();
BrName.Name = Convert.ToString(dr["BranchName"]);
Br.Add(BrName);
}
dr.Close();
}
}
return Br;
}
public class Branch
{
public string Name { get; set; }
}
End of Service file Code----
This is coded in the Form
ServiceClient client= new ServiceClient();
test.GetAllBranchCompleted += (s, ea) =>
{
cboBranch.ItemsSource = ea.Result;
};
client.GetAllBranchAsync();
My requirement is I want to populate all the Names of the Branches that are present in my database.With this code the combobox for BranchName is getting populated but not with the Database records but something like this CRUD.ServiceReference1.ServiceBranch.
CRUD is my solution Name.
Please correct me with this..
Thanks
To get just the name to appear in your ComboBox you need to result a List<string>. Here you are returning a List<Branch>.
So you either need to rework your service code or just extract a list of strings from your ea.Result.
cboBranch.ItemsSource = ea.Result.Select(b => b.Name).ToList();
(from memory)