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();
}
Related
I'm new to c# programming and have a problem retrieving data from database to a label text. Here is the code what I was trying to do.
private void label3_Click_1(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("Server=localhost; Database=car_rental; user=root; Pwd=; SslMode=none");
DataTable dTable = new DataTable();
con.Open();
MySqlDataReader dr = null;
MySqlCommand cmd = new MySqlCommand("Select * from login where username=" + username, con);
dr =cmd.ExecuteReader();
while (dr.Read())
{
label3.Text = (dr["username"].ToString());
}
con.Close();
}
The problem in your code is created by the concatenation of a string (username) to another string (the sql query). This is a well known source of problems, going from syntax errors (the engine is not able to parse correctly the query text) to a much worse problem known as Sql Injection.
The well known solution is to use parameters instead of concatenated strings
private void label3_Click_1(object sender, EventArgs e)
{
using(MySqlConnection con = new MySqlConnection("Server=localhost; Database=car_rental; user=root; Pwd=; SslMode=none"))
{
con.Open();
// A single string with a parameter placeholder
string sqlCmd = "Select * from login where username=#name";
using(MySqlCommand cmd = new MySqlCommand(sqlCmd, con))
{
// Associate a value to the required parameter
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = username;
using(MySqlDataReader dr =cmd.ExecuteReader())
{
// Supposing you have just one user with that name
if(dr.Read())
{
label3.Text = dr["username"].ToString();
}
else
{
label3.Text = "User not found!";
}
}
}
}
Notice how I have added the using statement around each disposable object required to query the database. This statement ensures that the objects involved are disposed at the end of their use freeing the valuable unmanaged resource kept during their usage.
I'm trying to display numbers of records (in table) using C# Windows form . Bud It display "1" as output for every time . Here is the code.
private void button1_Click(object sender, EventArgs e)
{
string constr = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Visual Studio/database.mdf;Integrated Security=True";
SqlConnection con = new SqlConnection(constr);
con.Open();
string query= "select Count(*) from Student where Name like '%b%' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
int count = 1;
while (dr.Read())
{count++;}
label1.Text ="Following records : "+count+" ";
}
selecting count(*) returns one record with the value of the column holding the number of rows in the table. You don't need to count the number of rows in the result, you just need to get it from the first (and only) row:
int count = 0;
if (dr.Read()) {
count = dr.GetInt32(0);
} else {
// something went horribly wrong. Throw an exception perhaps?
}
If you need to count all of your records, then you need to remove LIKE filter from the query.
You do not have to use SqlDataReader - the ExecuteScalar is enough.
For the start, your code should be:
private void button1_Click(object sender, EventArgs e)
{
string constr = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Visual Studio/database.mdf;Integrated Security=True";
SqlConnection con = new SqlConnection(constr);
con.Open();
string query= "select Count(*) from Student";
SqlCommand cmd = new SqlCommand(query1, con);
int count = (int)cmd.ExecuteScalar();
label1.Text ="Following records : "+count+" ";
}
Also, consider learning about using statement which enforces good practice for releasing and disposing resources.
Very important thing when you work with the database connections, transactions and commands.
SqlCommand with using statement
i think you should use rownum function it will display the number for each record for more info check this link http://docs.oracle.com/cd/B12037_01/server.101/b10759/pseudocolumns008.htm
Hey everyone pretty new to SQL Database functions but have been coding in c# for about a year now still not that great at it but I'm getting there!
I'm currently creating a football application and to Edit players and Matches i was wanting to use one drop down combo box to retrieve data from an SQL database which then would populate other text boxes and combo boxes. I've had a go at it myself but don't know where i'm going wrong.
On form load my connection opens i populate my datasets and i execute this method to populate my combobox
private void Navigate()
{
string showPlayers = "SELECT * From Add_Players";
SqlCommand cmdData = new SqlCommand(showPlayers, conn);
SqlDataReader myReader = cmdData.ExecuteReader();
while (myReader.Read())
{
comboEditPlayer.Items.Add(myReader[0]);
}
conn.Close();
}
After which in the combo box selected index changed method i have this code
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
string showPlayers = "SELECT * From Add_Players WHERE Player_ID ='"
+ comboEditPlayer + "' ;";
SqlCommand cmdData = new SqlCommand(showPlayers, conn);
SqlDataReader myReader = cmdData.ExecuteReader();
while (myReader.Read())
{
comboEditPlayerPos.Items.Add(myReader[1]);
txtEditPlayerName.Text = myReader[2].ToString();
txtEditPlayerSecond.Text = myReader[3].ToString();
comboEditPlayerStatus.Items.Add(myReader[4]);
}
conn.Close();
conn.Dispose();
}
catch (Exception comboFail)
{
MessageBox.Show(comboFail.ToString());
}
}
I've been told this code is open and i need to use parameterized queries for preventing hacker attempts which i have started but do not know what Parameter i should be adding to the code i have for this is below
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString =
ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
using (SqlConnection connection = new SqlConnection (connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT * From Add_Players WHERE Player_ID ="
+ comboEditPlayer.SelectedValue + "", connection))
{
command.Parameters.Add(new SqlParameter ("",));
}
}
}
All help is appreciated and please go easy on me :P
You could add a parameter to the collection with the value of your ComboBox, then execute the query and read back the values from the reader
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString =
ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
using (SqlConnection connection = new SqlConnection (connectionString))
using (SqlCommand command = new SqlCommand(
"SELECT * From Add_Players WHERE Player_ID =#id", connection))
{
connection.Open();
command.Parameters.AddWithValue("#id", comboEditPlayer.Text);
using(SqlDataReader myReader = command.ExecuteReader())
{
while (myReader.Read())
{
comboEditPlayerPos.Items.Add(myReader[1]);
txtEditPlayerName.Text = myReader[2].ToString();
txtEditPlayerSecond.Text = myReader[3].ToString();
comboEditPlayerStatus.Items.Add(myReader[4]);
}
}
}
}
I've a form in which I've data of Products of one store. i am accessing product Name and Price by just simply Providing Product code into other form, now here i want that when i open my Products form in which i have used list view to show already added products, i can easily click on any row , click edit button and the selected list view row becomes edit able , i simply update data in list view (by writing it in list view) and then click on save and it just automatically save data into my data base using update query..
the code through which i am loading products data in list view is :
private void frm4_Load(object sender, EventArgs e)
{
fnc_LoadProductsInfo(lvProducts);
}
private void fnc_LoadProductsInfo(ListView lv)
{
string sql;
sql = "";
sql += "SELECT * FROM ProductLog ORDER BY ItemNo";
SqlConnection con = new SqlConnection();
clsConnection clsCon = new clsConnection();
SqlCommand cmd = new SqlCommand();
SqlDataReader sdr;
clsCon.fnc_ConnectToDB(ref con);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
sdr = cmd.ExecuteReader();
lv.Items.Clear();
ListViewItem lvItem;
while (sdr.Read())
{
lvItem = new ListViewItem();
lvItem.Text = Convert.ToString(sdr.GetValue(sdr.GetOrdinal("ItemNo")));
lvItem.SubItems.Add(Convert.ToString(sdr.GetValue(sdr.GetOrdinal("ProductCode"))));
lvItem.SubItems.Add(Convert.ToString(sdr.GetValue(sdr.GetOrdinal("ProductName"))));
lvItem.SubItems.Add(Convert.ToString(sdr.GetValue(sdr.GetOrdinal("ProductPrice"))));
// lvItem.SubItems.Add(Convert.ToString(sdr.GetValue(sdr.GetOrdinal("TotalPrice"))));
//lvItem.SubItems.Add(Convert.ToString(sdr.GetValue(sdr.GetOrdinal("Password"))));
lv.Items.Add(lvItem);
lvItem = null;
}
// lblTotalRecords.Text = Convert.ToString(lv.Items.Count);
sdr.Close();
sdr = null;
cmd = null;
con.Close();
con = null;
}
is it possible to make list view editable in it's own column and if yes then how can i do it?? any other suggestion will also be appreciable ...
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.