I'm working in Visual Studio 2019 In c
I have problem with updating data to database
I use local Visual Studio SQL database
private void button1_Click(object sender, EventArgs e)
{
String source = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
con.Open();
String sqlSelectQuery = "SELECT * FROM [Table] WHERE ID = "+ int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Kor"].ToString());
label4.Text = (dr["Kor"].ToString());
label5.Text = (dr["Kor"].ToString());
int s = 11;
string y = (dr["Kor"].ToString());
label4.Text = (dr["Kor"].ToString());
x = Int32.Parse(label4.Text);
x = x + 0;
label6.Text = (x.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
String source = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
con.Open();
x = x + 1;
label6.Text = (x.ToString());
String st = "UPDATE supplier SET Kor = " + label6.Text + " WHERE Id = " + textBox1.Text;
}
Add these lines
SqlCommand cmd = new SqlCommand(st, con);
int result = cmd.ExecuteNonQuery();
Please put a breakpoint and check the value of st, is it generating the valid query.
I would suggest to use parameterized query to avoid sql injection.
Also, please avoid using Select *, please use columns.
Related
I Have a excel and I want Upload only four columns of that to SQL Table with a button.
The problem is when I repeat click the button all of that data will be duplicated but I Don't want that. I want only new data to be update.
My query:
protected void Button1_Click(object sender, EventArgs e)
{
int UserID;
int InsuID;
string Result;
int Year;
//** مسیر فایل اکسل**
String ExcelPath = #"D:\Insu_lab.xlsx";
//** کانکشن به آفیس**
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
UserID = Convert.ToInt32(dr[0].ToString());
InsuID = Convert.ToInt32(dr[1].ToString());
Result = dr[2].ToString();
Year = Convert.ToInt32(dr[3].ToString());
savedata(UserID, InsuID, Result, Year);
Label1.Text = "اطلاعات با موفقیت در دیتابیس ذخیره شد";
}
}
private void savedata(int UserID, int InsuID, string Result, int Year)
{
String query = "insert into tbl_Result(UserID,InsuID,Result,Year) values(" + UserID + ",'" + InsuID + "','" + Result + "','" + Year + "') ";
String mycon = "Data Source=MC6082; Initial Catalog=Insurance; Integrated Security=true";
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
Solution 1: When you clickedon button, that(button) disable the button.
Button1.disable = true;
When export ended:
Button1.disable = false;
Solution 2: you can use from jquery ajax in this part.
I have tried the following code but it throws exception "No value given for one or more required parameters".
protected void Button2_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select count(*) from quant_level1";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
while (i <= count)
{
string cmdstr = "select * from quant_level1 where id = i";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
con1.Close();
}
One mistake is within the select Statement:
You are trying to select an ID which you don't provide.
string cmdstr = "select * from quant_level1 where id = i";
Your select statement should look like:
string cmdstr = "select * from quant_level1 where id = " + i;
Your Loop-counter is/was within your string. It won't be replaced automatically.
try this -
work only if you are using Web Application
protected void Button2_Click(object sender, EventArgs e)
{
int i;
if (ViewState["count"] != null)
i = Convert.ToInt32(ViewState["count"].ToString());
else
i = 2; // assuming that it is your starting point as given in question
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select count(*) from quant_level1";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int)com1.ExecuteScalar();
if (i < count)
{
string cmdstr = "select * from quant_level1 where id = i";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
ViewState["count"] = i.ToString();
}
con1.Close();
}
This will do the trick in your case. happy coding :)
Since you want to fetch next row every time on clicking the button.
int i=2;
protected void Button2_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select * from quant_level1 where id ="+i;
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
if(reader.Read())
{
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
i++;
}
con1.Close();
}
Hello sir i wanna search the data using checkbox aur checkboxlist like if i select two checkbox then i wanna to get the data of both the checkbox id's this code is giving me only one data at a time. please give me a demo code for this type of query.
private void checkboxlistbind()
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\FlagBits\\Documents\\Visual Studio 2010\\WebSites\\checkboxlist\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True");
con.Open();
string query = "select * from student where id='" + CheckBox1.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
}
private void checkboxlistbind2()
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\FlagBits\\Documents\\Visual Studio 2010\\WebSites\\checkboxlist\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True");
con.Open();
string query = "select * from student where id='" + CheckBox2.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
checkboxlistbind();
}
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox2.Checked == true)
{
checkboxlistbind();
checkboxlistbind2();
}
You need to iterate through your checkboxlist and test the selected value for each item and build a string containing each of your options.
string queryparam = '';
for (int i=0; i<checkboxlist1.Items.Count; i++) {
if (checkboxlist1.Items[i].Selected)
{ queryparam += (queryparam.Length = 0) ? "id = " + checkboxlist1.Items[i].Text : " or id = " checkboxlist1.Items[i].Text }
}
This should give you an idea to start with.
I use C# Windows Form. i'm need auto number not duplicate.
I'm Import file excel to datagridview and Generate field 'id' for not duplicate.
But don't work.
Ex.
First Import.
ID | Name
P001 => Auto Gen | A
P002 => Auto Gen | B
Second Import.
ID | Name
P001 => Auto Gen But I need P003 | C
P002 => Auto Gen But I need P004 | D
Code:
SqlConnection Conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
StringBuilder sb = new StringBuilder();
SqlTransaction tr;
private void testExcel_Load(object sender, EventArgs e)
{
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
TextBox1.Text = openFileDialog1.FileName;
File.ReadAllText(TextBox1.Text);
}
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + TextBox1.Text + #";Extended Properties=""Excel 8.0; HDR=Yes; IMEX=1; ImportMixedTypes=Text; TypeGuessRows=0"" ";
OleDbCommand cmd = new OleDbCommand("SELECT * " + "FROM [SHEET1$]", conn);
DataSet ds = new DataSet();
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
ad.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception)
{
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
tr = Conn.BeginTransaction();
sb.Remove(0, sb.Length);
sb.Append("INSERT INTO tbl_Asset (AsId,AsName)");
sb.Append("VALUES (#Asid,#AsName)");
string sqlSave = sb.ToString();
cmd.CommandText = sqlSave;
cmd.CommandType = CommandType.Text;
cmd.Connection = Conn;
cmd.Transaction = tr;
cmd.Parameters.Clear();
cmd.Parameters.Add("#Asid", SqlDbType.VarChar).Value = dataGridView1.Rows[i].Cells[0].Value;
cmd.Parameters.Add("#AsName", SqlDbType.VarChar).Value = dataGridView1.Rows[i].Cells[1].Value;
cmd.ExecuteNonQuery();
tr.Commit();
}
MessageBox.Show("Insert Done", "Result", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void button3_Click(object sender, EventArgs e)
{
int cellnum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
cellnum = cellnum + 1;
dataGridView1.Rows[i].Cells[0].Value = txtID.Text + "000" + cellnum;
}
}
Thanks you so much for you time. :)
If you're doing this purely in SQL Server, you could add an identity column then add a computed column to give you your custom format:
alter table MyTable add MyNewColumn as 'P' + right('000' + cast(MyIdentColumn as varchar(3)), 3)
Note that this example will give unexpected results after your identity reaches 1000.
I enabled MARS and still cant execute two SqlDataReaders in one connection,i searched for a solution to enable MARS by default using RegEdit by couldnt find any solution and still getting that error : There is already an open DataReader associated with this Command which must be closed first.
Here is the code :
public partial class student_Courses : System.Web.UI.Page
{
string connectionString = "";
string query1 = "";
string query2 = "";
string courseName = "";
string chapterName = "";
string chapterVideoName = "";
string courseValue = "";
SqlDataReader sr2 = null;
protected void Page_Load(object sender, EventArgs e)
{
query1 = "SELECT * FROM Courses";
query2 = "SELECT * FROM Chapters WHERE value='" + courseValue + "'";
connectionString = "Data Source=Prince-PC;" +
"Initial Catalog=Elearning;" +
"Integrated Security=True;"+
"MultipleActiveResultSets=True";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand command1 = new SqlCommand(query1, con);
SqlCommand command2 = new SqlCommand(query2, con);
if (con.State == ConnectionState.Closed)
con.Open();
using (SqlDataReader sr1 = command1.ExecuteReader())
{
while (sr1.Read())
{
courseName = sr1["name"].ToString();
courseValue = sr1["value"].ToString();
sr2 = command2.ExecuteReader();
while (sr2.Read())
{
chapterName = TextBox3.Text = sr2["name"].ToString();
chapterVideoName = Label2.Text = sr2["video_name"].ToString();
}
}
}
con.Close();
}
}
You need to dispose of sr2 via a using statement as done in this MSDN MARS example
// The following line of code requires
// a MARS-enabled connection.
productReader = productCmd.ExecuteReader();
using (productReader)
{
while (productReader.Read())
{
Console.WriteLine(" " +
productReader["Name"].ToString());
}
}