How to retrieve data from database in label - c#

I wanat to retrieve student ID from database. Here is my code what i have tried but it is not displaying anything.
Thanks...
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True");
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
string str = "select * from StRecords where StID='" + Session["login"] + "'";
SqlCommand com = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Label11.Text = dt.Rows[0]["StID"].ToString();
}
}

If you want to take just StudentId from the database, then you just select that column and use ExecuteScalar property.
Code
protected void Button2_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True"))
{
con.Open();
string str = "select [StID] from StRecords where StID = #stdId;";
using (SqlCommand com = new SqlCommand(str, con))
{
com.Parameters.AddWithValue("#stdId", Session["login"]);
Label11.Text = com.ExecuteScalar().ToString();
}
}
}
Also always use parameters instead passing the value in single quotes to avoid SQL injection attack.
Also try to give the connection string in Web.Config file.

Related

Get Values from Database based on one textbox in a registration form

I am making a basic web form with basic fields like name, email, number.
I just want, when i enter the number, rest of the fields are populated in the other textboxes based on that number from sql server.
Any help would be appreciated.
Code is as follows :
string ConnectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
string cmd = "IF NOT EXISTS(Select * from tbl_registration where Email = #Email OR MobileNo = #MobileNo) insert into tbl_registration values(#FirstName, #LastName,#Email,#MobileNo,#Address_1,#Address_2,#City,#State)";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using(SqlCommand com = new SqlCommand(cmd, con))
{
com.Parameters.AddWithValue("#FirstName", txtfname.Text.Trim());
com.Parameters.AddWithValue("#LastName", txtlname.Text);
com.Parameters.AddWithValue("#Email", txtemail.Text);
com.Parameters.AddWithValue("#MobileNo", txtmob_no.Text);
com.Parameters.AddWithValue("#Address_1", txtaddress1.Text);
com.Parameters.AddWithValue("#Address_2", txtaddress2.Text);
com.Parameters.AddWithValue("#City", txtcity.Text);
com.Parameters.AddWithValue("#State", txtstate.Text);
con.Open();
int success = com.ExecuteNonQuery();
if (success > 0)
{
Response.Write("<script>alert('Registration successfull')</script>");
}
else
{
Response.Write("<script>alert('Registration Not Sucessfull')</script>");
}
}
}
}
You should write the method definition as shown below on the text box changed event.
This is not the complete query answer. Here is a reference for you.
using (SqlConnection conn = new SqlConnection(CSs))
{
string query = "Your SQL Query here";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "sometablename");
firstnametext.Text = Convert.ToString(ds.Tables["sometablename"].Rows[0]["Firstname"]);
}
Here you need to properly handle the null for the data table.

Query single data from SQLite to C# textbox or label

I have a single SQlite query that returns "10" to me but I couldn't send it to c# textbox1.text area. I found datagrid examples which work just fine but single value for textbox I could not handle it.
I tried changing datagrid areas to textbox but really I have no idea how to get value with sqlite
private SQLiteConnection con = new SQLiteConnection();
private SQLiteCommand com = new SQLiteCommand();
private SQLiteDataAdapter adapt = new SQLiteDataAdapter();
private DataSet ds = new DataSet();
private DataTable dt = new DataTable();
//private SQLiteDataReader dr = new SQLiteDataReader();
public void set_connection()
{
con = new SQLiteConnection();
con.ConnectionString = ("Data Source=data/lastix_db.s3db");
}
public void execute_q(string txtQuery)
{
set_connection();
con.Open();
com = con.CreateCommand();
com.CommandText = txtQuery;
com.ExecuteNonQuery();
con.Close();
}
public void load_data()
{
set_connection();
con.Open();
com = con.CreateCommand();
string comtext = "SELECT * FROM stok";
adapt = new SQLiteDataAdapter(comtext, con);
ds.Reset();
adapt.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
con.Close();
}
private void Button2_Click(object sender, EventArgs e)
{
set_connection();
string stokout = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
execute_q(stokout);
label16.Text = Convert.ToString(stokout);
label16.Text = //must be read "10" from sqlite
Insert update delete and all other datagrid solutions are ok but I'm really stuck on read single data and type it to textbox.
SQLiteConnection connect = new SQLiteConnection();
connect.ConnectionString = ("Data Source=data/lastix_db.s3db");
connect.Open();
string sql = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
SQLiteCommand cmd = new SQLiteCommand(sql, connect);
Int32 totalp = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
baglan.Close();
//MessageBox.Show("Your Balance is: " + totalp);
label16.Text = Convert.ToString(totalp);

how to search data in db

This code is working fine but when i search id like 121452, so it will call all numbers that have "1" or "2" in db. so i want it show only the exact id what i search
private void btn_search_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acap\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Student where No_ic = " + boxSearch.Text, con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
//dataGridView1.Visible = true;
}
Try this :
Updated: (Previously i forgot to bind dataset.)
private void btn_search_Click(object sender, EventArgs e) {
String bResult = boxSearch.Text;
string connectionString = "Data Source=.;Initial Catalog=sacbase;Integrated Security=True"; // add your conncetion string here
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM Student where No_ic =#val", connection);
cmd.Parameters.AddWithValue("#val", bResult);
SqlDataAdapter dataadapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "student_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "student_table";
}

How to insert value from gridview into database

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

Fetching data from SQL Server 2005 using c#

I would like to retrieve a particular column from a table when the values from two other columns are equal. My code is as follows. The four columns are id,destination,source,price.
I want to display the price when the destination and source are equal.
Could you please help me?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true");
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = new SqlCommand("select price from metro where source='" + textBox1.Text + "' and destination='" + textBox2.Text + "'", con);
da.Fill(dt);
for(int i=0;i<dt.Rows.Count;i++)
{
textBox3.Text = dt.Rows[0][3].Count.ToString();
}
}
I thing you are after this ....
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true"))
{
string query = "select price from metro where source= #Source and destination = #Destination";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Source", textBox1.Text);
cmd.Parameters.AddWithValue("#Destination", textBox2.Text);
con.Open();
object o = cmd.ExecuteScalar();
if(o != null && o != DBNull.Value)
{
string price = (string) o; //please cast the return type as required
textBox3.Text = price;
}
con.Close();
}
}
}

Categories

Resources