May I ask, how can I get error for this? It is so confusing. I get bug like this and I try to fix, but it does not work at all. I'm just a beginner.
namespace WindowsFormsApp1
{
public partial class Schedule : Form
{
public Schedule()
{
InitializeComponent();
}
MySqlConnection con = new MySqlConnection(#"Data Source=localhost;port=3306;Initial Catalog=Payroll;User Id=root;password=''");
MySqlDataReader dr;
int tc = 0;
private void Schedule_Load(object sender, EventArgs e)
{
datagrid();
fillsched();
}
public void datagrid()
{
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter("Select * from employee where Pstatus='Active'", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
con.Close();
}
public void fillsched()
{
con.Open();
MySqlDataReader dr;
MySqlCommand cmd = new MySqlCommand("select * from updateschedule ", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
int data = dr.GetInt32("empSched");
comboBox1.Items.Add(data);
}
con.Close();
}
public void getsched()
{
if (Int32.TryParse(comboBox1.SelectedItem.ToString(), out tc))
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from updateschedule where empSched=#empSched ", con);
cmd.Parameters.Add("#empSched", MySqlDbType.Int32).Value = tc;
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = dr["TimeIn"].ToString();
textBox3.Text = dr["TimeOut"].ToString();
label5.Text = tc.ToString();//to pass the data in the combobox1
}
con.Close();
}
}
public void view()
{
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
getsched();
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
view();
}
}
private void button1_Click(object sender, EventArgs e)
{
insert();
insertempsched();
}
public void insert()
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule (empSchedID,empID,empIN,empOut)VALUES(#empSchedID,#empID,#empIn,#EmpOut)", con);
cmd.Parameters.Add("#empSchedID", MySqlDbType.Int32).Value = label5.Text;
cmd.Parameters.Add("#empID", MySqlDbType.VarChar).Value = textBox1.Text;
cmd.Parameters.Add("#empIn", MySqlDbType.Date).Value = textBox2.Text;
cmd.Parameters.Add("#empOut", MySqlDbType.VarChar).Value = textBox3.Text;
execnonquery(cmd, "Data Inserted");
}
public void insertempsched()
{
con.Open();
MySqlCommand cmd = new MySqlCommand("Update employee set empSched=empSched where empID=#empID", con);
cmd.Parameters.Add("#empSchedID", MySqlDbType.Int32).Value = label5.Text;
cmd.Parameters.Add("#empID", MySqlDbType.VarChar).Value = textBox1.Text;
cmd.ExecuteNonQuery();
con.Close();
}
public void execnonquery(MySqlCommand sqc, string mymsg)
{
con.Open();
if (sqc.ExecuteNonQuery() == 1)
{
MessageBox.Show(mymsg);
}
else
{
MessageBox.Show("Query not Executed");
}
con.Close();
}
}
}
"Index was outside the bounds of the array" in c# always indicates that you are trying to get values based on column index number or row index number from datagrid or datatables or arrays and column or row does not exist at that position or index.
I think you are getting error at following line which exists in "view" method.
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
Also to catch the errors it's a good practice to use try catch blocks in all the methods.
You can modify your method like this
public void view()
{
try
{
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Related
I have a form from which brand can be added and edited but from different buttons but button for another function is disabled while operating one.
How to make the already selected items appear in the brand and category combo box and how to make the list of all the items are shown?
This is the form after the edit button is clicked.
This is the code of the form.
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace Project
{
public partial class AddProduct : Form
{
private SqlCommand cm = new SqlCommand();
private SqlConnection cn = new SqlConnection();
private DBConnection dbcon = new DBConnection();
private SqlDataReader dr;
private ProductList plist;
public AddProduct(ProductList pl)
{
InitializeComponent();
cn = new SqlConnection(dbcon.MyConnection());
plist = pl;
}
public void Clear()
{
tbPID.Clear();
tbDesc.Clear();
tbPrice.Clear();
cbBrand.Text = "";
cbCategory.Text = "";
tbPrice.Focus();
btnSave.Enabled = true;
btnUpdate.Enabled = false;
}
public void LoadCategory()
{
cbCategory.Items.Clear();
cn.Open();
cm = new SqlCommand("SELECT category FROM tblCategory", cn);
dr = cm.ExecuteReader();
while (dr.Read())
{
cbCategory.Items.Add(dr[0].ToString());
}
dr.Close();
cn.Close();
}
public void LoadBrand()
{
cbBrand.Items.Clear();
cn.Open();
cm = new SqlCommand("SELECT brand FROM tblBrand", cn);
dr = cm.ExecuteReader();
while (dr.Read())
{
cbBrand.Items.Add(dr[0].ToString());
}
dr.Close();
cn.Close();
}
private void AddProduct_Load(object sender, EventArgs e)
{
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Do you want to save this product?", " ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
string bid = "";
string cid = "";
cn.Open();
cm = new SqlCommand("SELECT id FROM tblBrand where brand like'" + cbBrand.Text + "'", cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows) bid = dr[0].ToString();
dr.Close();
cn.Close();
cn.Open();
cm = new SqlCommand("select id from tblCategory where category like'" + cbCategory.Text + "'", cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows) cid = dr[0].ToString();
dr.Close();
cn.Close();
cn.Open();
cm = new SqlCommand("INSERT INTO tblProduct(pcode, pdesc, bid, cid, price)VALUES(#pcode, #pdesc, #bid, #cid, #price)", cn);
cm.Parameters.AddWithValue("#pcode", tbPID.Text);
cm.Parameters.AddWithValue("#bid", bid);
cm.Parameters.AddWithValue("#pdesc", tbDesc.Text);
cm.Parameters.AddWithValue("#cid", cid);
cm.Parameters.AddWithValue("#price", tbPrice.Text);
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Product has been added successfully.");
Clear();
plist.LoadProducts();
this.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
Clear();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Do you want to update this product?", " ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
string bid = "";
string cid = "";
cn.Open();
cm = new SqlCommand("SELECT id FROM tblBrand where brand like'" + cbBrand.Text + "'", cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows) bid = dr[0].ToString();
dr.Close();
cn.Close();
cn.Open();
cm = new SqlCommand("select id from tblCategory where category like'" + cbCategory.Text + "'", cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows) cid = dr[0].ToString();
dr.Close();
cn.Close();
cn.Open();
cm = new SqlCommand("UPDATE tblProduct SET pdesc=#pdesc, bid=#bid, cid=#cid, price=#price where pcode like #pcode", cn);
cm.Parameters.AddWithValue("#pcode", tbPID.Text);
cm.Parameters.AddWithValue("#bid", bid);
cm.Parameters.AddWithValue("#pdesc", tbDesc.Text);
cm.Parameters.AddWithValue("#cid", cid);
cm.Parameters.AddWithValue("#price", double.Parse(tbPrice.Text));
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Product has been updated successfully.","Product Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
Clear();
plist.LoadProducts();
this.Dispose();
}
}
catch (Exception ex)
{
cn.Close();
MessageBox.Show(ex.Message);
}
}
}
}
I had used 2 controls to edit gridview inside.It shows error "input string was not in a correct format"
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fill_grd();
fill_gender();
}
}
public void fill_gender()
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_Gender_get", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
radiolist.DataValueField = "Gid";
radiolist.DataTextField = "Gname";
radiolist.DataSource = ds;
radiolist.DataBind();
}
con.Close();
}
public void fill_grd()
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_Login_get", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
grd.DataSource = ds;
grd.DataBind();
}
else
{
grd.DataSource = null;
grd.DataBind();
}
con.Close();
}
protected void grd_RowEditing(object sender, GridViewEditEventArgs e)
{
grd.EditIndex = e.NewEditIndex;
fill_grd();
}
protected void grd_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = int.Parse(grd.DataKeys[e.RowIndex].Value.ToString());
con.Open();
SqlCommand cmd = new SqlCommand("usp_Login_delete", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Lid", id);
cmd.ExecuteNonQuery();
con.Close();
fill_grd();
}
protected void grd_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox TB1 = (TextBox)grd.Rows[e.RowIndex].FindControl("edittxtname");
RadioButtonList RBL1 = (RadioButtonList)grd.Rows[e.RowIndex].FindControl("editradiolist");
int id = int.Parse(grd.DataKeys[e.RowIndex].Value.ToString());
con.Open();
SqlCommand cmd = new SqlCommand("usp_Login_update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Lid", id);
cmd.Parameters.AddWithValue("#Name", TB1.Text);
cmd.Parameters.AddWithValue("#Gender", RBL1.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
grd.EditIndex = -1;
fill_grd();
}
protected void grd_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grd.EditIndex = -1;
fill_grd();
}
protected void savebtn_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_Login_insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", txtname.Text);
cmd.Parameters.AddWithValue("#Gender", int.Parse(radiolist.SelectedValue));
cmd.ExecuteNonQuery();
con.Close();
fill_grd();
}
}
}
Not sure where your error occurs and the code you've pasted is really not relevant for your question but I'll try to answer anyway.
You need to check the datatype for the radio button, it's probably not a bool or int. It seems you are setting datatypes from the results you get from the database and I would guess you need to change the datatype by checking the stored procudure usp_Login_get and the datatype you are setting for the radiobutton column.
My Combobox contains the name of a waiter.
When I allot the table to the selected waiter its status become true but the combobox item doesn't change.
programming on page_load:---
private void frmTableAllotment_Load(object sender, EventArgs e)
{
dtTmPkr.Value = System.DateTime.Now;
cmd = new SqlCommand("Select name from waiterentry2 where status='false'", con);
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
cmbWaiter.Items.Add(dr["name"]);
}
dr.Close();
cmd = null;
con.Close();
}
coding on save button for waiter status= true on allot button:
private void btnAllocate_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("update waiterentry2 set status='true' where name=#name", con);
cmd.Parameters.AddWithValue("name", dgvDetails.Rows[i].Cells[0].Value);
cmd.ExecuteNonQuery();
con.Close();
}
Problem is after you change the database you haven't refresh or reload the combobox databinding.
I would re factor your code as below and call the load data method after database update.
private void frmTableAllotment_Load(object sender, EventArgs e)
{
dtTmPkr.Value = System.DateTime.Now;
LoadComboBox();
}
private void btnAllocate_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("update waiterentry2 set status='true' where name=#name", con);
cmd.Parameters.AddWithValue("name", dgvDetails.Rows[i].Cells[0].Value);
cmd.ExecuteNonQuery();
con.Close();
LoadComboBox();
}
private void LoadComboBox()
{
while(cmbWaiter.Items.Count >0)
cmbWaiter.Items.RemoveAt(0);
cmd = new SqlCommand("Select name from waiterentry2 where status='false'", con);
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
cmbWaiter.Items.Add(dr["name"]);
}
dr.Close();
cmd = null;
con.Close();
}
Try to call he code which you have written in form load after successful db operation in btnAllocate_Click event
I Planned to insert image in database. But there is some problem while inserting i.e (image format : input string was not in correct format). Please help me . Thanks in advance.
Error comes in this line -> int count = cmd.ExecuteNonQuery();
I have created the database with img (column name) Blob (datatype).
public partial class check1 : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection("server=localhost; database=esample; uid=root;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
protected void btnupload_Click(object sender, EventArgs e)
{
if (fileupload.HasFile)
{
int length = fileupload.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileupload.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
string imagename = imgname.Text;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO brand (imgname,img) VALUES (#imagename,#imagedata)", con);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Blob).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
con.Close();
if(count==1)
{
BindGridData();
imgname.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
private void BindGridData()
{
MySqlConnection con = new MySqlConnection("server=localhost; database=esample; uid=root;");
MySqlCommand command = new MySqlCommand("SELECT imgname,img,bid from brand", con);
MySqlDataAdapter daimages = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}
}
Using a class named Player with the id, name and photo values.
public static bool createUser(Player player)
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO tbuser (id,sName,lbFoto) VALUES (#id,#name,#foto)", dbConnection);
cmd.Parameters.AddWithValue("#id", player.id).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("#name", player.Name).DbType = DbType.String;
cmd.Parameters.AddWithValue("#foto", player.Image).DbType = DbType.Binary;
try
{
if (dbConnection.State == ConnectionState.Closed)
dbConnection.Open();
cmd.ExecuteNonQuery();
dbConnection.Close();
return true;
}
}
catch { }
finaly
{
if (dbConnection.State == ConnectionState.Open)
dbConnection.Close();
}
return false;
}
Then for retrieval the data:
public static Player loadUser(string ID)
{
var table = Select(dbConnection, "tbuser", "id = " + ID);
Player player = new Player();
foreach (DataRow row in table.Rows)
{
player.id = (int)row[0];
player.Name = row[1].ToString();
player.Image = (byte[])row[2];
return player;
}
return null;
}
The function Select. This is an extra ;)
public static DataTable Select(MySqlConnection con, string tableName, string expressionWhere)
{
string text = string.Format("SELECT * FROM {0} WHERE {1};", tableName, expressionWhere);
MySqlDataAdapter cmd = new MySqlDataAdapter(text, con);
DataTable table = new DataTable();
if (con.State == ConnectionState.Closed)
con.Open();
try
{
cmd.Fill(table);
}
catch (Exception){}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
return table;
}
I can add, edit, delete database using listbox. But I want to do it using DatagridView I already bind it to my database.
How do I add,edit,delete update my database in datagridview using codes?
These are my codes:
namespace Icabales.Homer
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\homer\documents\visual studio 2010\Projects\Icabales.Homer\Icabales.Homer\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
SqlDataAdapter da;
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}
private void bindgrid()
{
string command = "select * from info";
da = new SqlDataAdapter(command, cn);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.info' table. You can move, or remove it, as needed.
this.infoTableAdapter.Fill(this.database1DataSet.info);
cmd.Connection = cn;
loadlist();
bindgrid();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "")
{
cn.Open();
cmd.CommandText = "insert into info (id,name) values ('" + txtid.Text + "' , '" + txtname.Text + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record Inserted");
cn.Close();
txtid.Text = "";
txtname.Text = "";
loadlist();
}
}
private void loadlist()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "select * from info";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
txtid.Text = listBox1.SelectedItem.ToString();
txtname.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "")
{
cn.Open();
cmd.CommandText = "delete from info where id = '"+txtid.Text+"'and name = '"+txtname.Text+"'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Deleted");
loadlist();
txtid.Text = "";
txtname.Text = "";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "" & listBox1.SelectedIndex != -1)
{
cn.Open();
cmd.CommandText = "update info set id='"+txtid.Text+"',name='"+txtname.Text+"'where id='"+listBox1.SelectedItem.ToString()+"' and name='"+listBox2.SelectedItem.ToString()+"'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Updated");
loadlist();
txtid.Text = "";
txtname.Text = "";
}
}
}
}
I have a dataGridView and a button on a form. When I do any editing, insertion or deletion in the dataGridView1, the code below does the magic
public partial class EditPermit : Form
{
OleDbCommand command;
OleDbDataAdapter da;
private BindingSource bindingSource = null;
private OleDbCommandBuilder oleCommandBuilder = null;
DataTable dataTable = new DataTable();
public EditPermit()
{
InitializeComponent();
}
private void EditPermitPermit_Load(object sender, EventArgs e)
{
DataBind();
}
private void btnSv_Click(object sender, EventArgs e)
{
dataGridView1.EndEdit(); //very important step
da.Update(dataTable);
MessageBox.Show("Updated");
DataBind();
}
private void DataBind()
{
dataGridView1.DataSource = null;
dataTable.Clear();
String connectionString = MainWindow.GetConnectionString(); //use your connection string please
String queryString1 = "SELECT * FROM TblPermitType"; // Use your table please
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = queryString1;
try
{
da = new OleDbDataAdapter(queryString1, connection);
oleCommandBuilder = new OleDbCommandBuilder(da);
da.Fill(dataTable);
bindingSource = new BindingSource { DataSource = dataTable };
dataGridView1.DataSource = bindingSource;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I have implemented a solution that inserts/updates/deletes data in MS SQL database directly from DataGridView.
To accomplish this I have used the following events: RowValidating and UserDeletingRow.
It is supposed that you have
SqlConnection _conn;
declared and initialized.
Here is the code:
private void dgv_RowValidating( object sender, DataGridViewCellCancelEventArgs e )
{
try
{
if (!dgv.IsCurrentRowDirty)
return;
string query = GetInsertOrUpdateSql(e);
if (_conn.State != ConnectionState.Open)
_conn.Open();
var cmd = new SqlCommand( query, _conn );
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning );
}
}
public string GetInsertOrUpdateSql( DataGridViewCellCancelEventArgs e )
{
DataGridViewRow row = dgv.Rows[e.RowIndex];
int id = 0;
int.TryParse( row.Cells["Id"].Value.ToString(), out id );
DateTime dob;
DateTime.TryParse( row.Cells["Dob"].Value.ToString(), out dob );
string email = row.Cells["Email"].Value.ToString();
string phone = row.Cells["Phone"].Value.ToString();
string fio = row.Cells["Fio"].Value.ToString();
if (id == 0)
return string.Format( "insert into {0} Values ('{1}','{2}','{3}','{4}')", "dbo.People", fio, dob.ToString( "dd-MM-yyyy" ), email, phone );
else
return string.Format( "update {0} set Fio='{1}', Dob='{2}', Email='{3}', Phone='{4}' WHERE Id={5}", "dbo.People", fio, dob.ToString( "dd-MM-yyyy" ), email, phone, id );
}
private void dgv_UserDeletingRow( object sender, DataGridViewRowCancelEventArgs e )
{
try
{
int id = 0;
int.TryParse( e.Row.Cells["Id"].Value.ToString(), out id );
string query = string.Format( "DELETE FROM {0} WHERE Id = {1}", "dbo.People", id );
var cmd = new SqlCommand( query, _conn );
if (_conn.State != ConnectionState.Open)
_conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning );
}
}
Hope this helps.
I have the same kind of project at home, I do not have the source code with me but if needed I can check somewhere this weekend to see what exactly I have done, but I believe it's some of the following:
Since you are using a dataset and a dataadapter this can be achieved very easily.
As long as your DataGridView1 has the properties enabled for users to add/delete/edit rows you could use the following code.
DataAdapter.Update(DataTable);
//in your code this would be:
da.Update(dt);
The DataAdapter.Update() Method will auto generate any insert/update/delete commands needed to update the results of your fill query compared with the current data in your datagridview.
You can set those commands (properties) as well in case you prefer to modify them, though this is not necessary.
This only works ofcourse after a user has made changes to the DataGridView. Add this code to a simple button and see if you have any luck. It definitly was something this simple :)