Label Text save to database - c#

i want to create one label, Label name empty.
now i change label name using this code :
MainMenu frm = new MainMenu();
try
{
con = new SqlConnection(cs.DBConn);
con.Open();
String sql = "SELECT SSUserID from SSUserInformation where UserName like '" + txtUserName.Text + "%'";
cmd = new SqlCommand(sql, con);
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
frm.lbluserid.Text = rdr[0].ToString();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
then i save label name to database using this code :
insert into UserInfo(UserID) Values(frm.lbluserid.Text);
the problem is recored save but is empty not any value stored into database

what if you change your sql
String sql = "INSERT INTO UserInfo(UserID) " +
"SELECT SSUserID from SSUserInformation where UserName like '" + txtUserName.Text + "%'";
EDIT
string SQL = "INSERT INTO [UserInfo] ([UserID]) VALUES (#UserName) " +
" SELECT [SSUserID] FROM [SSUserInformation] WHERE [UserName] LIKE #UserName + '%' ";
SqlCommand cmd = new SqlCommand(SQL);
cmd.Parameters.AddWithValue("#UserName", txtUserName.Text);
cmd.ExecuteNonQuery();

public static string SaveSales(string aa, string bb, string cc, string dd, string ee, string ff, string gg,string hh,string ii)
{
OleDbConnection myConnection = GetConnection();
string myQuery = "INSERT INTO Sales VALUES ( '" + aa + "' , '" + bb + "','" + cc + "','" + dd + "','" + ee + "' ,'" + ff + "' ,'" + gg + "','" + hh + "','" + ii + "' );";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);

Related

Cannot Find Table 0 from other form

Tried to move data from one form to another and there is a problem with the table. Yes I found such themes with a mistake, and tried to correct himself, but something went wrong.
using (SqlConnection conn = new SqlConnection("Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True"))
{
SqlDataAdapter comm = new SqlDataAdapter("INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('"+ tName.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + cbName.Text + "' and Stage = '" + cbStage.Text + "'), '" + tSurname.Text + "', '" + tMiddle.Text + "', '" + tPas.Text + "', '" + cbClinic.Text + "', '" + tAge.Text + "')", conn);
conn.Open();
DataSet ds = new DataSet();
//ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
comm.Fill(ds);
Form1 form = new Form1();
form.DataGrid.DataSource = ds.Tables[0]; //?
}
string connectionString = "Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
try
{
command.CommandText = "INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('" + metroTextBox1.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + metroComboBox1.Text + "' and Stage = '" + metroComboBox2.Text + "'), '" + metroTextBox2.Text + "', '" + metroTextBox3.Text + "', '" + maskedTextBox1.Text + "', '" + metroComboBox3.Text + "', '" + metroTextBox5.Text + "')";
command.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Added");
//here is a DataSet
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
transaction.Rollback();
}
}
You are expecting results to be returned from your query, but what you do is just INSERT statement.
For inserting values you should use ExecuteNonQuery method of SqlCommand (see this for reference).
Then, assign another command: SELECT to get the results, then you can fill DataSet with the result and then you can fill DataGridView with it.
Also: you are rpone to SQL injection, use parametrized query to prevent yourself from such threat (see this for reference).

Why is my SQL code in C# not working?

I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:
And here is my code:
public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
{
if (beoordelingBest < beoordeling)
{
titelBest = titel;
beoordelingBest = beoordeling;
}
string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
command = new SqlCommand(queryString, con);
Can someone please help me with this? I can't figure it out.
Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
If you have multiple queries each unique parameter value should have its own parameter name/value
Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
Never reuse connections as global objects, create, use, and destroy them when needed.
Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.
var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT #a1Voornaam, #a1Achternaam, FilmID from Films WHERE titel = #title";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
command.Parameters.Add(new SqlParameter("#a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
command.Parameters.Add(new SqlParameter("#achternaam", SqlDbType.VarChar){Value = achternaam});
command.Parameters.Add(new SqlParameter("#title", SqlDbType.VarChar){Value = title});
con.Open();
command.ExecuteNonQuery();
}
Perhaps one of your values is ');
That would terminate the INSERT statement early, and cause the error.
|
V
INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');
You should use SqlParameters instead of string concatenation.
Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
try
{
string query = "insert into UserDetail(Name,Address)
values('" + txtName.Text + "','" + txtAddress.Text + "');";
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.SelectCommand.ExecuteNonQuery();
con.Close();
lblmessage.Text = "Data saved successfully.";
}
catch
{
con.Close();
lblmessage.Text = "Error while saving data.";
}
}

Cannot Select Between No error can someonehelp me check string?

i want to input date value in textbox1 and textbox2 but i think im not sure about string cmd can someone help me check issuse ? please
try
{
con = new SqlConnection(MyConnectionString);
con.Open();
int tp;
string sqlstr = "select * from viewReC_store where stk_date_time between '" + TextBox1.Text + "' and '" + TextBox2.Text + "'";
cmd = new SqlCommand(sqlstr, con);
SqlDataReader sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
}
catch (Exception ex)
{
Label4.Text = "ERROR"+ex ;
}
con.Close();
Blockquote string sqlstr = "select * from viewReC_store where stk_date_time between '" + TextBox1.Text + "' and '" + TextBox2.Text + "'";
i guess this line
ok im got it
string sqlstr = "select * from viewReC_storeFG where stk_date_time between '" + TextBox1.Text + "' and '" + TextBox2.Text + "'";
thank u for read and reply
close..

Not able to read the text box value

I am assigning the value to the variable from the text box on the page during the pageupload event of AjaxFileUpload1.The problem is that, I am not getting the value from the text box to my variable even though no error throws.My variables are
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
Any idea why AjaxFileUpload1_UploadComplete is not able to read text box value
My cs Code is:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
Please help me
I spent some time last week investigating this question but in the end couldn't find an easy solution for this. The OP in that question solved it by storing values in the Session but for this to work you would still need to cause a postback at some stage.
There apparently was functionality planned for the AjaxFileUpload control to pass values in the Context Keys collections but this was never implemented. This question describes how to implement this yourself though.
I think I saw another question around the same topic and the OP solved it by changing to using the AsyncFileUpload control but I stand to be corrected...
i think you need to add !Page.IsPostBack to your code. like this
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
if(!Page.IsPostBack)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
}

i m getting error in the following cede. (System.Data.OleDb.OleDbException: ORA-00933: SQL command not properly ended)

protected void save_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
try
{
string connString = "Provider=OraOLEDB.Oracle;Data Source=127.0.0.1;User ID=SYSTEM;Password=SYSTEM;Unicode=True";
conn = new OleDbConnection(connString);
conn.Open();
string strQuery = "update login set fname ='" + TextBox4.Text + "' and lname='" + TextBox5.Text + "' and place='" + TextBox6.Text + "' and dob='" + TextBox7.Text + "' where uname='" + Label1.Text + "'";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
OleDbDataReader obReader = obCmd.ExecuteReader();
}
catch (OleDbException ex)
{
Response.Write("Send failure: " + ex.ToString());
}
catch (Exception exe)
{
Response.Write(exe.Message);
}
finally
{
if (null != conn)
{
conn.Close();
}
}
}
the update query syntax is wrong.
You cannot use AND while setting multiple columns. It should be seperated by comma.
string strQuery = "update login set fname ='" + TextBox4.Text + "',lname='" +
TextBox5.Text + "',place='" + TextBox6.Text + "',dob='" + TextBox7.Text +
"' where uname='" + Label1.Text + "'";
The values must be separated with a comma and there is one big problem in this code. Imagine what happens when someone puts the following into TextBox4:
' where 1 = 1 --
The result would be a table where all entries would be overwritten
update login set fname ='' where 1 = 1 --', lname='bla' ....
Use DbParameter instead:
string strQuery = #"
update LOGIN set
FNAME = :FNAME,
LNAME = :LNAME,
PLACE = :PLACE,
DOB = :DOB
where
UNAME = :UNAME
";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
obCmd.Parameters.AddWithValue(":FNAME", TextBox4.Text);
obCmd.Parameters.AddWithValue(":LNAME", TextBox5.Text);
obCmd.Parameters.AddWithValue(":PLACE", TextBox6.Text);
obCmd.Parameters.AddWithValue(":DOB", TextBox7.Text);
obCmd.Parameters.AddWithValue(":UNAME", Label1.Text);
OleDbDataReader obReader = obCmd.ExecuteReader();
For Oracle the : should indicate a parameter (it's a # for Sybase and MS SQL). I named all params like the target columns, but you can use other names of course.

Categories