updating sql server database using c# in asp.net - c#

There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?
protected void Page_Load(object sender, EventArgs e) {
rno.Text = Request.QueryString["rno"];//rno is a textbox
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "select fname from table1 where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if (reader.Read()) {
fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
}
reader.Close();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
protected void modify_Click(object sender, EventArgs e) {
fName.ReadOnly = false;
}
protected void savechanges_Click(object sender, EventArgs e) {
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update table1 set fname=#fname where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", sfname);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}

I have tried your code which executed fine and updated database table as well.
I have tried like below :
string connectionString = #"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update TestTable set fname=#fname where rno =rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", "Test");
command.Parameters.AddWithValue("#rno", "rno");
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
Another way I have tried.
using (SqlConnection connection = new SqlConnection(connectionString ))
{
connection.Open();
var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";
using (SqlCommand cmd = new SqlCommand(queryText, connection))
{
responseResults = await cmd.ExecuteNonQueryAsync();
}
connection.Close();
}
Hope it would help

After searching for a while, I found out that this code was executing perfectly. The only problem was that everything was inside the page_Load() method and thus the page was reloading everytime I updated the database and thus removing the small window to edit the textboxes. The appropriate solution was to associate this code with some button event rather than with the page_Load() event.

Related

How to retrieve data from database in label

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.

Save a picture into database without binding source

I tried to save a picture into database using Sqlcommand . When I save , there is an exception throw said " Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query."
here is the code:
private void btn_save_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd1= new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
string squ1;
squ1 = "INSERT INTO Customer (cus_name, cus_address, cus_Image)Values('" + textBox1.Text + "' , '" + textBox2.Text + "', '"+pictureBox1 .Image +"');";
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\ProgramData\MyDB\TestingDB.mdf;Integrated Security=True;Connect Timeout=30";
con.Open();
cmd1.Connection = con;
cmd1.CommandText = squ1;
cmd1.ExecuteNonQuery();
con.Close ();
}
// the browser button to get a picture
private void btn_browseImage_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
if (f.ShowDialog () == DialogResult .OK )
{
pictureBox1.ImageLocation = f.FileName;
}
You have to pass the image data as a varbinary parameter to the query:
using (var con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\ProgramData\MyDB\TestingDB.mdf;Integrated Security=True;Connect Timeout=30"))
using (var cmd1 = new SqlCommand("INSERT INTO Customer (cus_name, cus_address, cus_Image)Values(#name, #address, #image);", con))
{
var imageData = new MemoryStream();
pictureBox1.Image.Save(imageData, pictureBox1.Image.RawFormat);
cmd1.Parameters.AddWithValue("#name", textBox1.Text);
cmd1.Parameters.AddWithValue("#address", textBox2.Text);
cmd1.Parameters.Add("#image", SqlDbType.VarBinary).Value = imageData.ToArray();
con.Open();
var result = cmd1.ExecuteNonQuery();
}
And you should really read up on how to use SqlCommand to avoid future SQL injection.
The statement '"+pictureBox1.Image +"' will actually call pictureBox1.Image.ToString() which is not the binary content of the image. Use SqlParameters to add your binary data. You can find a solution here...

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

After accessing the database, the rest of statements do not work

I have a textBox (txtName) and a label (lblMassage).
When the Form loads user can type his name in the textbox and submit his data into the database.
My button click event is
private void btnSubmit_Click(object sender, EventArgs e)
{
string name = txtName.Text;
String sql = "insert into UserName values ('" + name + "')";
SqlCommand com = new SqlCommand(sql, ConnectionManager.Connection());
com.ExecuteNonQuery();
lblMessage.Text = "Record added successfully";
txtName.Text = "";
}
class ConnectionManager
{
public static SqlConnection Connection()
{
string ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\chathuranga\documents\visual studio 2012\Projects\SansipProtoType\SansipProtoType\SansipDataBase.mdf;Integrated Security=True";
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
return con;
}
}
when I check the database manually the value of txtName is in the table UserName which means the value user typed is added to the database successfully.
But the following two statements won't work.
lblMessage.Text = "Record added successfully";
txtName.Text = "";
Can anyone give me a solution?
private void btnSubmit_Click(object sender, EventArgs e)
{
static SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\chathuranga\documents\visual studio 2012\Projects\SansipProtoType\SansipProtoType\SansipDataBase.mdf;Integrated Security=True";);
string name = txtName.Text;
conn.Open();
SqlCommand myCommand = new SqlCommand("INSERT INTO UserName VALUES (#Username)", conn);
myCommand.ExecuteNonQuery();
lblMessage.Text = "Record added successfully";
txtName.Text = "";
conn.close();
}
use this code
string name = txtName.Text;
var connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\chathuranga\documents\visual studio 2012\Projects\SansipProtoType\SansipProtoType\SansipDataBase.mdf;Integrated Security=True";
var connection = new SqlConnection(ConnectionString);
connection.Open();
var sql = "INSERT INTO UserName VALUES (#Username)";
using(SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Username", name);
command.ExecuteNonQuery();
}
connection.Close();
connection.Dispose();
lblMessage.Text = "Record added successfully";
txtName.Text = "";
Updated

Adding just Unique Data to Gridview

I have a table like this. Columns --> (MUSTERI, AVUKAT, HESAP (Unique))
My page design like this.
Simply, first dropdown is MUSTERI, second dropdown is AVUKAT, when i click EKLE (it means ADD) button, automaticyly getting HESAP (unique) and showing on gridview.
What i want is, if any user try to add a data which they are the same HESAP, geting an error.
For example;There is a data "2M LOJİSTİJ" "ALİ ORAL" "889" in my gridview.
Someone try to add a data like "2M LOJİSTİK" "EMRA SARINÇ" "889" showing an error and don't add to table.
My Add_Click button code is
protected void Add_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
And my first dropdown MUSTERI (getting HESAP auto by this field)
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesapNo = DropDownList1.SelectedItem.Value;
string query = "select A.HESAP_NO from YAZ..MARDATA.S_TEKLIF A where A.MUS_K_ISIM = '" + hesapNo + "'";
SqlCommand cmd = new SqlCommand(query, myConnection);
if (DropDownList1.SelectedValue != "0")
{
Add.Enabled = true;
Label1.Text = cmd.ExecuteScalar().ToString();
}
else
{
Add.Enabled = false;
}
Label1.Visible = false;
myConnection.Close();
}
How can i blocking insert data which already have the same HESAP?
first check HESAP is exist or not in #AVUKAT then insert new entry.
protected void Add_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text.Trim();
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
string strsql= "SELECT * FROM AVUKAT WHERE HESAP = " + hesap;
SqlCommand com = new SqlCommand(strsql, myConnection);
SqlDataReader dread = com.ExecuteReader();
dread.read();
if(dread.HasRows)
{
myConnection.Close();
return;
}
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}

Categories

Resources