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
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 have stored some number data under column name Value in the tblV table of my database. I want to put the data from that column Value into textbox1.
But whenever I click the button it shows Column 'Value' does not belong to table error even though there is column Value in the table. What is causing this problem?
The first one is class and second one is the code on button click event.
public DataTable GetMaxno(decimal Licenseno)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;");
string sql = "select Max(Value) from tblv where Licenseno=#licenseno";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Licenseno",Licenseno );
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
da.Fill(DT);
return DT;
}
tryv tv = new tryv();
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = tv.GetMaxno(Convert.ToDecimal(textBox2.Text));
if (dt.Rows.Count > 0)
{
textBox1.Text= dt.Rows[0]["Value"].ToString();
}
}
Reason might be that your query does not return any aliases as Value. You can solve this with select Max(Value) as Value but instead of that, use ExecuteScalar instead which is exactly what you want. It returns first column of the first row.
A few things more;
Use using statement to dispose your connection and command.
Do not use AddWithValue. It may generate unexpected and surprising result sometimes. Use Add method overloads to specify your parameter type and it's size.
public int GetMaxno(decimal Licenseno)
{
using(var con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;")
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "select Max(Value) from tblv where Licenseno = #licenseno";
cmd.Parameters.Add("#licenseno", SqlDbType.Decimal).Value = Licenseno;
con.Open();
return (int)cmd.ExecuteScalar();
}
}
Then you can do;
textBox1.Text = tv.GetMaxno(Convert.ToDecimal(textBox2.Text)).ToString();
try
string sql = "select Max(Value) as Value from tblv where Licenseno=#licenseno";
I am trying to populate a listbox in C# from a table in sql server. The table is set up as:
tblTables
TableID int
SeatingCapacity int
CurrentCapacity int
The code I am trying to use is:
private void fillListBox()
{
String connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter();
String commandString = "SELECT TableID, SeatingCapacity, CurrentCapacity from tblTables";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
conn.Open();
cmd.CommandText = commandString;
cmd.Connection = conn;
dr = cmd.ExecuteReader();
lstTableList.Items.Clear();
lstTableList.BeginUpdate();
while (dr.Read())
{
lstTableList.Items.Add(dr.GetInt32(0) + " - " + dr.GetInt32(1) + " - " + dr.GetInt32(2));
}
lstTableList.EndUpdate();
dr.Close();
conn.Close();
}
And the code for the parent form to transfer is:
private void mnuFormsTables_Click(object sender, EventArgs e)
{
frmTables aTables = new frmTables();
aTables.MdiParent = this;
aTables.Show();
aTables.Focus();
}
I call fillListBox() is the form load of frmTables. However when I put a break point on
String connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
It shows that right after that line the code jumps to the parent form at
aTables.Show();
Any help would be greatly appreciated. I am also not sure if that is the proper way to populate the listbox either. Preferably it would be nice if the listbox could show the table ID and add "Full" beside it if the current capacity >= seating capacity.
The github repo URL for this is https://github.com/resistince/StaufferRestaurant
EDIT: If I use:
String connectionString = Properties.Settings.Default.StaufferRestaurantConnectionString;
instead of using the ConfigurationManager it works. I have System.Configuration.dll as a reference and the proper using statement so I don't know why it doesn't work right.
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();
}
}
}
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();
}