I'm trying to insert data to a SQL Server with a dataGridView.
Here's what I have now in my buttonSave_Click :
string conString = "xxxxxxxx";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
foreach (DataGridViewRow row in dataGridViewStock.Rows)
{
SqlCommand insert = new SqlCommand("INSERT INTO stock_test(size,quantity,codeArticleComponent) VALUES (#size,#quantity,#codeArticleComponent)", con);
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
insert.Parameters.AddWithValue("#size", row.Cells[0].Value);
insert.Parameters.AddWithValue("#quantity", row.Cells[1].Value);
insert.Parameters.AddWithValue("#codeArticleComponent", labelComponentChosen.Text);
}
insert.ExecuteNonQuery();
insert.Parameters.Clear();
}
For now this piece of code has a weird behavior because it throws an exception System.Data.SqlClient.SqlException : Must declare the scalar variable "#size" but what I wrote in the cells is still added to the database.
very likely command cannot be executed on last DataGridView row, which is reserved for new item input. and all previous items are inserted properly.
it happens because (row.Cells[0].Value != null && row.Cells[1].Value != null) check for that row returns false and parameters are not added. the next statement insert.ExecuteNonQuery(); tries to run a command without required parameters and fails
create and execute insert command only for valid rows:
foreach (DataGridViewRow row in dataGridViewStock.Rows)
{
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
SqlCommand insert = new SqlCommand("INSERT INTO stock_test(size,quantity,codeArticleComponent) VALUES (#size,#quantity,#codeArticleComponent)", con);
insert.Parameters.AddWithValue("#size", row.Cells[0].Value);
insert.Parameters.AddWithValue("#quantity", row.Cells[1].Value);
insert.Parameters.AddWithValue("#codeArticleComponent", labelComponentChosen.Text);
insert.ExecuteNonQuery();
}
}
string conString = "xxxxxxxx";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
foreach (DataGridViewRow row in dataGridViewStock.Rows)
{
SqlCommand insert = new SqlCommand();
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
insert.Parameters.AddWithValue("#size", row.Cells[0].Value);
insert.Parameters.AddWithValue("#quantity", row.Cells[1].Value);
insert.Parameters.AddWithValue("#codeArticleComponent", labelComponentChosen.Text);
}
insert = ("INSERT INTO stock_test(size,quantity,codeArticleComponent) VALUES (#size,#quantity,#codeArticleComponent)", con);
insert.ExecuteNonQuery();
insert.Parameters.Clear();
}
The Error is occur as you are using the variable before declaring them. Please Declare them prior with value before using into the Query.
This should do what you want.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlCommand sCommand;
SqlDataAdapter sAdapter;
SqlCommandBuilder sBuilder;
DataSet sDs;
DataTable sTable;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Stores";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
sCommand = new SqlCommand(sql, connection);
sAdapter = new SqlDataAdapter(sCommand);
sBuilder = new SqlCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "Stores");
sTable = sDs.Tables["Stores"];
connection.Close();
dataGridView1.DataSource = sDs.Tables["Stores"];
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void new_btn_Click(object sender, EventArgs e)
{
dataGridView1.ReadOnly = false;
save_btn.Enabled = true;
new_btn.Enabled = false;
delete_btn.Enabled = false;
}
private void delete_btn_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
sAdapter.Update(sTable);
}
}
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
}
}
You can find LOTS of great examples from the link below.
http://csharp.net-informations.com/datagridview/csharp-datagridview-database-operations.htm
Related
First, I'm really sorry about my English pronounciation. I have a datagridview, and i connect it to sql server which has been dip into my project in visual studio. However, when i save info in datagridview, it works but in database it is not saved in my database in sql server. Can you help me, please
And this is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lab3_Bai09
{
public partial class Form1 : Form
{
SqlConnection cnn = null;
string connetionString;
public Form1()
{
InitializeComponent();
connetionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\QLSV.mdf;Integrated Security=True";
cnn = new SqlConnection(connetionString);
cnn.Open();
cnn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
txtB2.Text = txtB1.Text;
}
private void button2_Click(object sender, EventArgs e)
{
txtB1.Text = txtB2.Text;
}
private void Save_Click(object sender, EventArgs e)
{
cnn.Open();
SqlCommand sqlCommand;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = "";
string sex = "";
if(checkBox1.Checked == true)
{
sex = "Nam";
}
else
{
sex = "Nu";
}
string[] subjectList = txtB1.Text.Split('\n');
int countSubject = subjectList.Length;
sql = $"insert into SINHVIEN(MSSV, HOTEN, CHUYENNGANH, GIOITINH, SOMON) values ('{textBox1.Text}', '{textBox2.Text}', '{comboBox1.Text}', '{sex}', '{countSubject}')";
sqlCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Đã thêm mới dữ liệu thành công!");
this.sINHVIENTableAdapter1.Fill(this.qLSVDataSet1.SINHVIEN);
textBox1.Clear();
textBox2.Clear();
checkBox1.Checked = false;
checkBox2.Checked = false;
txtB1.Clear();
txtB2.Clear();
cnn.Close();
}
private void Delete_Click(object sender, EventArgs e)
{
cnn.Open();
DialogResult result = MessageBox.Show("Bạn có muốn xóa dòng đã chọn?", "Delete", MessageBoxButtons.YesNoCancel);
if (result == DialogResult.Yes)
{
SqlCommand sqlCommand;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = "";
int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
string c = selectedRow.Cells[0].Value.ToString();
sql = $"delete from SINHVIEN where MSSV = {c}";
sqlCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Xóa dữ liệu thành công");
this.sINHVIENTableAdapter1.Fill(this.qLSVDataSet1.SINHVIEN);
}
cnn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'qLSVDataSet1.SINHVIEN' table. You can move, or remove it, as needed.
this.sINHVIENTableAdapter1.Fill(this.qLSVDataSet1.SINHVIEN);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult result = MessageBox.Show("Bạn có muốn thoát?", "Exit", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
Application.Exit();
}
else
{
e.Cancel = true;
}
}
else
{
e.Cancel = true;
}
}
}
}
It looks like you are just pulling values from text boxes and a combo box. There is a line for this.sINHVIENTableAdapter1.Fill(this.qLSVDataSet1.SINHVIEN); but where are those declared? I don't see you calling anything that writes the data back to the database from that adapter or dataset. After you declare the sqlCommand, you write a new instance of an sql command into the adapter, do you mean to do that?
sqlCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
I will say that you are leaving yourself wide open for SQL injection. The SQL INSERT should be handled more like this:
sql = $"insert into SINHVIEN(MSSV, HOTEN, CHUYENNGANH, GIOITINH, SOMON) values (#mssv, #hoten, #chuy, #sex, #countsub)";
sqlCommand = new SqlCommand(sql, cnn);
sqlCommand.Parameters.AddWithValue("#mssv", textBox1.Text);
sqlCommand.Parameters.AddWithValue("#hoten", comboBox1.Text);
sqlCommand.Parameters.AddWithValue("#chuy", textBox2.Text);
sqlCommand.Parameters.AddWithValue("#sex", sex);
sqlCommand.Parameters.AddWithValue("#countSub", countSubject);
adapter.InsertCommand = sqlCommand;
adapter.InsertCommand.ExecuteNonQuery();
See this post for how to bind a datagridview to a datatable: How to bind Dataset to DataGridView in windows application.
I'm trying to add some data from a SQLite database, inside a ListView.
I'm having some difficulties as I want to insert all the data of the column and not a single record.
TEST CODE:
Form1.cs {Load}
private void home_form_Load(object sender, EventArgs e)
{
listView1.Refresh();
listView1.View = View.Details;
listView1.Columns.Add("ID");
listView1.Columns.Add("Grado");
listView1.Columns.Add("Cognome");
listView1.Columns.Add("Nome");
listView1.Columns.Add("Status");
}
Form1.cs {menu_button_gestionepax}
private void menu_button_gestionepax_Click(object sender, EventArgs e)
{
menu_button_dashboard.BackColor = System.Drawing.Color.DeepSkyBlue;
panel_dashboard.Visible = false;
gestionepersonale_panel.Visible = true;
menu_button_gestionepax.BackColor = System.Drawing.Color.Blue;
listView1.Refresh();
ListViewItem lst = new ListViewItem();
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
listView1.Items.Add(lst);
/*
string[] row = { LoadUsers.ManagerFindid(), LoadUsers.ManagerFindid() };
var listViewItem = new ListViewItem(row);
infobox_listview.Items.Add(listViewItem);
*/
}
LoadUsers.cs
public dynamic string ManagerFind()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var select = cnn.Query($"select id from utenti");
if (select.Any())
{ return select[0].ToString(); }
else return "wrong";
}
}
I have also done various other tests and one of the difficulties in some cases is to call string ManagerFind() from LoadUsers.cs
Try something like this to get your rows and columns from your sql i know this is how you do it in SQL im sure there is a similar way to do it with sqlLite
using (SqlConnection connection = new SqlConnection(_sqlConnectionStringFromUserImput))
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
SqlCommand sqlCommand =
new SqlCommand(
"select id from utenti",
connection)
{
CommandType = CommandType.Text,
CommandTimeout = 20
};
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
DateTime datetimefield = reader.GetFieldValue<DateTime>(0);
string stringField = reader.GetFieldValue<string>(1);
}
}
reader.Close();
}
connection.Close();
}
Update should be updating the data in the confirm table with the given parameters. However no input gets updated/inputted despite there being no errors.
When the exact same query is inputted into the SQL Server Management Studio there is no errors and the rows are updated.
Why is the table not being updated?
There are 3 columns in the table - orderid (which is passed from another table) and then staffid and confirmed which should both be NULL - and are - until the rows are updated. orderid = int not null, staffid = int, confirmed = string.confirm database
The view is a left outer join, meaning that it shows the values that need to be update by the by.
[sql][2]
database diagram
Form
How can this be fixed, its been like this for two days.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace ComicBookShop
{
public partial class orders_confirm : Form
{
public orders_confirm()
{
InitializeComponent();
}
//database details
string connString = "Data Source = BLAH BLAH BLAH";
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide();
ManagmentMain fm = new ManagmentMain();
fm.Show();
}
private void orders_confirm_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM staff_view", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Set AutoGenerateColumns False
dataGridView5.AutoGenerateColumns = true;
dataGridView5.DataSource = dt;
}
}
}
con.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
{
MessageBox.Show("Please fill textboxes");
return;
}
//database details
string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand command = con.CreateCommand())
{
try
{
con.Open();
command.CommandText = "Update dbo.confirm set staffid=#staffid, confirmed=#confirmed where orderid =#orderid";
command.Parameters.AddWithValue("#orderid", txtorder.Text);
command.Parameters.AddWithValue("#staffid", txtstaff.Text);
command.Parameters.AddWithValue("#confirmed", txtConfirmed.Text);
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated");
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
}
this is the part of the code where the data should be inserted
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
{
MessageBox.Show("Please fill textboxes");
return;
}
//database details
string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand command = con.CreateCommand())
{
try
{
con.Open();
command.CommandText = "Update dbo.confirm set staffid=#staffid, confirmed=#confirmed where orderid =#orderid";
command.Parameters.AddWithValue("#orderid", txtorder.Text);
command.Parameters.AddWithValue("#staffid", txtstaff.Text);
command.Parameters.AddWithValue("#confirmed", txtConfirmed.Text);
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated");
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Try setting parameters with their corresponding data types:
command.Parameters.Add("orderid", SqlDbType.Int);
command.Parameters["orderid"].Value = int.Parse(txtorder.Text);
Do the same for staffid.
I think the issue is you are passing string where int is expected.
I Bind Data to a DataGridview using the following code
private void BindGrid()
{
try
{
string constr = "Data Source=INSPIRE-1;" +
"Initial Catalog=testdatabase;" +
"User id=testuser;" +
"Password=tester;";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM mytable", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
if (flag == false)
{
flag = true;
DataGridViewButtonColumn uninstallButtonColumn = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Edit";
uninstallButtonColumn.Text = "Edit";
dataGridView1.Columns.Insert(4, uninstallButtonColumn);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
I Update the selected record by hooking to a button click event in the datagridview row like this
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex ==4)
{
button4.Enabled = false;
try
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[0].Value;
using (SqlConnection conn = new SqlConnection(constr))
{
try
{
conn.Open();
SqlDataReader myReader = null;
string commandText = "select * from mytable where name= #name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("#name", orderId);
myReader = command.ExecuteReader();
while (myReader.Read())
{
textBox1.Text = myReader["name"].ToString();
textBox2.Text = myReader["age"].ToString();
textBox3.Text = myReader["phone"].ToString();
textBox4.Text = myReader["address"].ToString();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
catch (Exception error)
{
}
}
}
Now i update the values using the code below
private void button5_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(constr))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE mytable SET name=#NewName,age=#NewAge,phone=#NewPhone,Address=#NewAddress" +
" WHERE name=#oldname", conn))
{
cmd.Parameters.AddWithValue("#NewName", textBox1.Text);
cmd.Parameters.AddWithValue("#NewAge", textBox2.Text);
cmd.Parameters.AddWithValue("#NewPhone", textBox3.Text);
cmd.Parameters.AddWithValue("#NewAddress", textBox4.Text);
cmd.Parameters.AddWithValue("#oldname", orderId);
try
{
int rows = cmd.ExecuteNonQuery();
MessageBox.Show("Updated Successfully");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
BindGrid();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
button4.Enabled=true;
}
But after i click the Update Button then click on the Button Column corresponding to a Row e.ColumnIndex always returns 0.
What im i doing wrong?
UPDATE :
Please see the screenshot
Rahul's Answer will work but looks like orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[0].Value; should be modifiled to get Cells[1].Value and not 0 as 0 is the button cell from 2nd time onwards. But for 1st time you need to use 0 as then button is at index 4. Try below changes.
As far as I understand, issue is after update, you call the BindGrid again and since flag is true it just sets the datasource again for the grid and not generating button again thus button gets moved to index 0 followed by the datatable columns.
Another way to solve is modify your code a bit like
dataGridView1.Columns.Insert(0, uninstallButtonColumn);
dataGridView1.Columns[0].DisplayIndex = 4;
And then in CellClick event check for e.ColumnIndex == 0. This help you in showing the button at the position you want and always the click work as the columnindex never changes.
you can check button index like below without comparing its index:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
//TODO - Button Clicked - Execute Code Here
}
}
I have a problem, probably you guys in this forum could help me.
Here is my problem:
I want to show the MessageBox that say there is no data in datagridview, you cannot delete it.
I already can delete the data in the datagridview, but when the datagridview contains 0 data, and i click delete "button", it is error. The error is: Object reference not set to an instance of an object. NullReferenceException
Here is the code that pointed by the error:
int rowNum = dataGridView1.CurrentRow.Index;
Here is the code:
private void Delete(object sender, EventArgs e)
{
DataTable dt = (DataTable) dataGridView1.DataSource;
int rowNum = dataGridView1.CurrentRow.Index;
int id = Convert.ToInt32(dt.DefaultView[rowNum]["ID"]);
dt.DefaultView[rowNum].Delete();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "DELETE FROM [Table] WHERE [ID] = #ID";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("#ID", id);
cmd.ExecuteNonQuery();
}
if (choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
sound.Play();
MessageBox.Show("Deleted Successfully!", "Deleted");
if (rowNum == 0)
{
bool rowIsEmpty = true;
foreach (DataGridViewCell cell in dataGridView1.CurrentRow.Cells)
{
if (cell.Value != null)
{
rowIsEmpty = false;
break;
}
}
if (rowIsEmpty)
{
System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
sounds.Play();
MessageBox.Show("Tidak ada Data di Baris ini!", "Error");
}
else
{
Delete(sender, e);
}
}
}
}
}
Does anyone knows how to fix it?
Try like this dt.Rows.count > 0 means that there is data in data table if not there is no data in datatable , if data was present you can do your operation . dt.Rows.count will give the rows count in data table
DataGridView.CurrentRow is usable only when you set DataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect. Otherwise you have to get the current row by this:
int rowNum = dataGridView1.CurrentCellAddress.Y;
var currentRow = dataGridView1.Rows[rowNum];
UPDATE
Looks like that you use a DataTable as DataSource for your dataGridView1, you should take the benefit of Adapter in ADO.NET. This code is just some modifying your current code which in fact updates data in 2 phases: 1. Remove row from DataTable as well as from DataGridView 2. Remove the actual row in database.
private void Delete(object sender, EventArgs e)
{
DataTable dt = (DataTable)dataGridView1.DataSource;
int rowNum = dataGridView1.CurrentCellAddress.Y;
if(rowNum == -1) {
MessageBox.Show("There is no row selected!");
return;
}
int id = Convert.ToInt32(dt.DefaultView[rowNum]["ID"]);
//check if row is empty, simply return
if(IsRowEmpty(rowNum)){
System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
sounds.Play();
MessageBox.Show("There is no data in the selected row", "Error");
return;
}
//Remove the row
dt.DefaultView[rowNum].Delete();
dt.AcceptChanges(); //<-- Because you don't use Adapter, call this to restore the row state.
//Remove the underlying row in database
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "DELETE FROM [Table] WHERE [ID] = #ID";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("#ID", id);
cmd.ExecuteNonQuery();
}
if (choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
sound.Play();
MessageBox.Show("Deleted Successfully!", "Deleted");
}
}
}
//method to check if a row is empty
private bool IsRowEmpty(int index){
return dataGridView1.Rows[index].Cells.OfType<DataGridViewCell>()
.All(c=>c.Value == null);
}
I found the following condition quite useful
if(dataGridView1.DataSource!=null)
{
// do something
}