C# Windows Form
I have a button that removes the selected row from the dataGridView.
I also want the button to retrieve the selected rows "ordre" column value, so I can use it in a query that deletes the order from the sql table.
Here is what my code looks like:
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
//SQL connection
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
//SQL QUERY
command.CommandText = "DELETE FROM bestillinger WHERE ordrenr = #ordre";
command.Parameters.AddWithValue("#ordre",dataGridView1.SelectedRows[0].Cells["ordre"].Value.ToString())
con.Open();
var ordre = command.ExecuteScalar();
con.Close();
But it doesn't work! No record was deleted
After delete the row you can not get the value. So change your code like this
//SQL connection
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt
+ "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security
Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
//SQL QUERY
command.CommandText = "DELETE FROM bestillinger WHERE ordrenr = #ordre";
command.Parameters.AddWithValue("#ordre",dataGridView1.
SelectedRows[0].Cells["ordre"].Value.ToString())
con.Open();
var ordre = command.ExecuteScalar();
con.Close();
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
It is wrong logic.
Since the row has been removed by RemoveAt(),
you cannot get a wrong row from dataGridView1.SelectedRows[0].
I think you want this.
private void grdform1_CellClick(object sender, DataGridViewCellEventArgs e)
{
If(e.ColumnIndex==0 ||e.ColumnIndex==1)
{
txtshowcolunm.text=e.ColumnIndex;
}
else
{
txtshowcolunm.text=e.ColumnIndex;
}
}
Related
I've been trying to update the values from a sql database that's set as a data source in my windows form datagridview, but end up updating all rows instead.
I've been working on creating a basic task manager app for a development course that I'm enrolled in.
I'm having a hard time figuring out where the problem is located. I think that my code may not be properly set to the selected row?
I've supplied the code below, any and all help would be appreciated. If anyone need further clarification shoot me a message on the chat. throws a thumbs up
My Current Code:
private void UpdateBtn_Click(object sender, EventArgs e)
{
//Update button [almost done - data is not updating correctly]
string connectionString = "Data Source =ULTRA-COMPUTER; Initial Catalog =test; Persist Security Info =True; User ID = sa; Password = 12345";
SqlConnection con = new SqlConnection(connectionString);
string queryStatement = "SELECT * FROM testtask";
if (Task.Text != "" && Date.Text != "")
{
SqlCommand cmd = new SqlCommand(queryStatement, con);
DataTable task = new DataTable("testtask");
SqlDataAdapter ada = new SqlDataAdapter(cmd);
con.Open();
cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "' ";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Task", Task.Text);
cmd.Parameters.AddWithValue("#Date", Date.Text);
cmd.ExecuteNonQuery();
TaskData.DataSource = task;
MessageBox.Show("Update Inserted!");
ClearTxt();
}
else
{
MessageBox.Show("Please Enter A Task/DueDate To Update");
}
con.Close();
}
First add a hidden column for the primary key of your database table in datagridview. And now when you want to update the selected row that you have edited it use that primary key in where condition of your query.
cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "WHERE [TaskId]=#TaskId";
cmd.Parameters.AddWithValue("#TaskId", TaskIdFromDatagridview);
I think the problem is in this line
cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "' ";
You've not added the where clause that's why it'll update all rows in the table.
You must add a where clause.
For example you've taskid as primary key in this table and want to update a task with taskid 999 then your query must be
cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "' where taskid = 999 ";
I'm stuck on a issue where I need to backup my database via Winforms. I managed to find a sample SQL code in order to achieve this task.
My query here :
SqlConnection CON = new SqlConnection("Data Source=DBS\\DB;Initial Catalog=" + metroTextBox1.Text + ";Integrated Security=True");
Sql = "BACKUP DATABASE " + metroComboBox1.Text + " TO DISK = '" + metroTextBox4.Text + "\\" + metroComboBox1.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";
I have no idea how to proceed next. What should I use in this scenario? (ExecuteScalar, ExecuteNonQuery..etc)
Any help would be appreciated.
Note that Date time is also there in back up file name.
You define the SQL command to execute, and then instantiate a SqlCommand. Since the SQL statement isn't expected to return any data (a result set etc.), use ExecuteNonQuery:
string Sql = "BACKUP DATABASE " + metroComboBox1.Text + " TO DISK = '" + metroTextBox4.Text + "\\" + metroComboBox1.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";
using(SqlConnection CON = new SqlConnection("Data Source=DBS\\DB;Initial Catalog=" + metroTextBox1.Text + ";Integrated Security=True"))
using(SqlCommand cmdBackup = new SqlCommand(Sql, CON))
{
// open connection, execute command, close connection
CON.Open();
cmdBackup.ExecuteNonQuery();
CON.Close();
}
The general code:
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var comm = conn.CreateCommand())
{
comm.CommandType = CommandType.Text;
comm.CommandText = "BACKUP DATABASE...";
comm.ExecuteNonQuery();
}
}
I wrote the query for inserting data to MySQL table "Persons":
SqlConnection con = new SqlConnection();
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
But it's not working. I have one connection for the whole database, but it's not working for a specific table. How I can create a connection between specific table to query in C#?
What is it? SqlConnection con = new SqlConnection() you need to pass a connection string which comprises DBname, username, pasword, server name ... etc; you are not passing those information anywhere then how can you expect it to connect to your database without having the information.
Pass the connection string either in constructor or using the property.
SqlConnection con = new SqlConnection(connection_string)
(OR)
SqlConnection con = new SqlConnection();
con.ConnectionString = connection_string;
There are different ways to insert data into the tables. I suggest to use parametrized sql query to keep safe from malicious occurrence.
Firstly you should have a ConnectionString something like this:
string connectionString = "Persist Security Info=False;User ID=UserName;Password=YourPassword;Server=ServerName";
And than:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO TableName (Col1, Col2, ColN) VALUES (#Col1, #Col2, #ColN)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Col1", txtName.Text);
cmd.Parameters.AddWithValue("#Col2", txtPhone.Text);
cmd.Parameters.AddWithValue("#ColN", txtAddress.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
Try this code. Please edit your credentials before trying.
Replace localhost with SQL server instance name, user id with your MySQL server instance user id, password with your MySQL server instance password and testdb with your database name. It should work fine.
string connectionString = #"server=localhost;user id=admin;password=admin;database=testdb;";
SqlConnection con = new SqlConnection(connectionString);
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
I managed to create my own "save, update, delete" program with SQL after watching a video.
I have an issue, if I click "update" without having the "IndexNumber" in the database, nothing will happen.
Can anybody advise me on how to improve my "update" button? Perhaps if the data does not exist, the program can prompt the user with a message box instead of doing nothing. Like "IndexNumber does not exist therefore unable to update"
My update code
SqlConnection con = new SqlConnection(
#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath +
"\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand(#"UPDATE GlennTeoStudents SET IndexNumber = '" +
numIN.Value + "',Name = '" + txtName.Text + "',Age ='" + txtAge.Text +
"',HandPhoneNumber = '" + txtHP.Text + "',GPA = '" + numGPA.Value +
"' WHERE (IndexNumber='" + numIN.Value + "')", con);
cmd.ExecuteNonQuery();
con.Close();
SqlCommand.ExecuteNonQuery() returns the number of rows affected (int).
You could check on the return value:
SqlCommand.ExecuteNonQuery(asd)
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
if (!(rowsAffected > 0))
{
throw new ArgumentException(<Your Message>);
}
Then just catch the exception wherever you call the method and display your messagebox with
MessageBox.Show(<Your Message>)
try
{
.....
con.Open();
SqlCommand cmd = new SqlCommand(#"Select count(*) from GlennTeoStudents
WHERE (IndexNumber='" + numIN.Value + "')", con);
int count1 = cmd.ExecuteScalar();
if (count1 != 0)
{
do your update
}
else
{
give your message box
}
}
I am working on a Desktop application. I developed a form in which user enters data. When he clicks the submit button the data is saved in a database name PakReaEstat. The problem is the data is not inserted in the table and I get an error: SqlException was Unhandled.
When I click the Submit button it prompts error.
The code behind the button is as following:
protected void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo");
con.Open();
SqlCommand cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime)" +
"values (" + Convert.ToInt32(textBox1.Text) + ",'" +
textBox2.Text + "','" +
textBox4.Text + "'," +
textBox5.Text + "," +
textBox6.Text + "," +
textBox7.Text + "," +
textBox8.Text +
"," + textBox3.Text + ")", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Insertion successfully done");
}
Check you connection string and the SQL insert statement.
I recommend that you use sql parameters instead of the the textbox text property as value directly.
Beacause this is a common vulnerability, called SQL injection.
I also recommend to use using statement to ensure the connection is closed.
using (var con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo"))
{
con.Open();
using (var cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime)" + "values (#Application#,#LDAReg#, ... )", con))
{
cmd.Parameters.AddWithValue("#Application#", Convert.ToInt32(textBox1.Text));
cmd.Parameters.AddWithValue("#LDAReg#", textBox2.Text);
// add the other parameters ...
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Insertion successfully done");
There is problem in your SqlConnection
Make sure that your connection string is correct
SqlConnection con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo");
It should come like
SqlConnection con = new SqlConnection("Data Source=ADMIN3-PC;Initial Catalog=master;Integrated Security=True");
Always put your code in try... catch block if you are doing transaction with datatbase
If your connetion to databse is established and no issue there then
You are missing single quotes on last five textboxes. I suppose that last five columns are of type nvarchar in ur datatbse
change command to
SqlCommand cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime) values (" + Convert.ToInt32(textBox1.Text) + ",'" + textBox2.Text + "','" + textBox4.Text + " ','" + textBox5.Text + "','" + textBox6.Text+ "','" +textBox7.Text+ "','"+textBox8.Text +"','"+textBox3.Text+"')", con);