i am using asp.net C# SQL to create a webpage.I need to list out a courseID to let user choose, but it list out two time same value in dropdownlist
S1111
S2222
S3333
S1111
S2222
S3333
,someone help
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn;
SqlDataReader dtr;
SqlCommand cmd;
string Connnection = ConfigurationManager.ConnectionStrings["ELearing"].ConnectionString;
conn = new SqlConnection(Connnection);
if (!Page.IsPostBack)
{
//Get Staff Information
conn.Open();
string cmdString = "SELECT DISTINCT CourseID FROM Schedule WHERE(StaffID = #scheduleStaffID)";
cmd = new SqlCommand(cmdString, conn);
cmd.Parameters.AddWithValue("#scheduleStaffID", Session["UserID"].ToString());
dtr = cmd.ExecuteReader();
while (dtr.Read())
{
ddlCourse.Items.Add(dtr["CourseID"].ToString());
}
dtr.Close();
conn.Close();
}
}
Try these
1.Do you get duplicates when you do externally SELECT DISTINCT CourseID FROM Schedule WHERE StaffId = 1
2.use breakpoints to check additional post backs.
3.Try ddlCourse.Items.Clear just before your while loop.
Related
This is my code and I'm new to C# and trying to learn, basically I have a project where specialists are being scheduled in their specialty using fullcalendar, but when I created the dropdownlist for specialty and then made a listbox for the specialist in each specialty being selected it keeps saying that there's an error on cmd.ExecuteScalar(); What am I doing wrong?
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String CS = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT id, name, active, modifiedDate, note FROM sldb.dbo.Services", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if(this.DropDownList1.SelectedItem.Value != "0")
{
String CS = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using(SqlCommand cmd = new SqlCommand("select firstName from sldb.dbo.Specilist where serviceID= #serviceID", con))
{
using(SqlDataAdapter da = new SqlDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("#serviceID", this.DropDownList1.SelectedItem.Value);
con.Open();
object firstName = cmd.ExecuteScalar();
con.Close();
this.ListBox1.Text = firstName.ToString();
}
}
}
}
else
{
this.ListBox1.Text = "Please select name from list";
}
}```
If the error is on ExecuteScalar, there is something wrong with your query. I'm noticing Specialist is spelled wrong in the select statement. Try correcting that and let me know if that helps.
note that executeScalar return the first column of the first row in the dataset. Try wrap the executescalar in a try catch
try
{
object firstName = cmd.ExecuteScalar();
}
catch(Exception error)
{
//display error message error.Message;
}
Step through the code, I'd be tempted to put the value in a string to see what Scalar is returning.
string strPeek = cmd.ExecuteScalar().ToString();
Also, run the SQL separately to be sure the query is not erroneous.
i have 2 drop down lists and DB in my web application project. in the DB i have domain table and subDomain table. in the subDomain table i have foreign key to the column DomainId in domain table.
i populate the 1st droplist with data from domain (im using DomainId as datavalue and DomainName as datatext/ here is the code:
protected void Page_Load(object sender, EventArgs e)
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["SampleConnectionString"].ToString();
conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT DomainId , DomainName FROM Domain",conn);
conn.Open();
DropDownList1.DataTextField = "DomainName";
DropDownList1.DataValueField = "DomainId";
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataBind();
}
now when the user select item from the droplist i want to populate the 2nd droplist according to the item that was selected, but its not working.
here is the 2nd part of code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["SampleConnectionString"].ToString();
conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT SubDomainName, SubDomainId FROM SubDomain where DomainId= #id", conn);
cmd.Parameters.AddWithValue("#id", DropDownList1.SelectedValue);
conn.Open();
DropDownList2.DataTextField = "SubDomainName";
DropDownList2.DataValueField = "SubDomainId";
DropDownList2.DataSource = cmd.ExecuteReader();
DropDownList2.DataBind();
conn.Close();
}
Set AutoPostBack property of your DropDownList1 control to true. If you already set that, but still have an error, post your .aspx file also
I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}
If i find the 3 "Yes" in my table for a given ID then i am sending an email. So as you can see the code below is using the querystring as parameter and using that in my select statement but what i want to do is use the selected ID in the DetailView instead of the query-string. Here is the code that uses the query-sting:
protected void Check_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT count(*) from MyTable WHERE ID =#ID And (field1='Yes' And field2='Yes' And field3='Yes')", con);
cmd.Parameters.Add("#ID", Request.QueryString["ID"]);
cmd.Connection = con;
con.Open();
int result = (int)cmd.ExecuteScalar();
if (result == 1)
{
send email...
}
and here is the updated code that i modified and tried to use the DetailView ID but does not work properly, what am i doing wrong here pls help:
protected void Check_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
string ID = Detailview1.Rows[0].Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT count(*) from MyTable WHERE ID =#ID And (field1='Yes' And field2='Yes' And field3='Yes')", con);
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID;
cmd.Connection = con;
con.Open();
int result =(int) cmd.ExecuteScalar();
if (result == 1)
{
send email...
}
Looks like you are always looking same row which is the header in most of the case.
string ID = Detailview1.Rows[0].Cells[1].Text;
Instead of this you should use parameters of the event like e if you set every thing correctly you can get the ID by e.Keys. You can check the value of it in debug mode.
I have a (Sql Server 2008) table called Courses with course_id,course_name and course_description as its fields
In the front end, I have a text box and a search button. In the text box, when I give a course name (even a part of it)..in the button click event, all the course names should show up.
How do I code this in C#? Any help would be appreciated..
you can select from sql table with where statement
eg, "whre course_name = 'a'"
a means it will return all course name with a character a
for eg, matehmatics
can search for details about * thing in google.
First of all, you should use "LIKE" operator in sql command in order to list all the results containing the criteria.
Secondly, you should use SqlDataReader given that you are only retrieving values.
Thirdly, you should use a parameter in order to prevent sql injection.
Since you did not specify how you want to display the results, I populate a list from the results in my sample code below. I hope this helps you and future viewers.
private void button1_Click(object sender, EventArgs e)
{
List<string> Courses = new List<string>();
SqlConnection con = new SqlConnection("the connection string here");
SqlDataReader reader;
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT courseName, courseDescription FROM db.Courses WHERE CourseName LIKE %#CourseName%";
cmd.Parameters.AddWithValue("#CourseName", textBox1.Text);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
string course = reader["CourseName"].ToString();
course += ", " + reader["CourseDescription"].ToString();
Courses.Add(course);
}
reader.Close();
foreach (string course in Courses)
{
//wherever and however you would like to display
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("select Processor,HDD,RAM,Display,Graphics,OS,processor,hdd,ram,display,os,opticaldrive,warranty,price,other,graphics,images,Warranty,Price,Images,other from System where CompanyName='"+companyname.Text+"'",con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
processor.Text = dr.GetValue(3).ToString();
}
con.Close();
}