I have this form that takes these information from user #ID, #From, #To, #Title, #Message. Then it insert them into a database table.
How can I delete a certain data using the #ID? User will have a dataGridView1 with all the datatable, then by getting the CurrentCell it will delete this certain data.
private void delet_button_Click(object sender, EventArgs e)
{
int i = dataGridView1.CurrentCell.RowIndex;
string strid = dataGridView1[0, i].Value.ToString();
//MessageBox.Show(strid);
int id = Convert.ToInt32(strid);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete * from MessagesTable where [ID]=#ID ";
cmd.Parameters.AddWithValue("#ID", id);
MessageBox.Show("Message was deleted");
BindGrid();
}
You are almost certainly going about this all wrong. You should start with a DataTable. If appropriate, you can query the database to populate it by calling Fill on a data adapter. You can then bind the table to your DataGridView via a BindingSource, which you would add in the designer, e.g.
var table = new DataTable();
using (var adapter = new SqlDataAdapter("SQL query here", "connection string here"))
{
adapter.Fill(table);
}
BindingSource1.DataSource = table;
DataGridView1.DataSource = BindingSource1;
You then mark the current row as deleted by calling RemoveCurrent on the BindingSource. That will hide the row in the grid but it won't affect the database at that stage. To save the changes to the database, you call Update on an appropriately configured data adapter, which may be the same one you called Fill on in the first place. You could call Update to save the change as soon as the user deletes the row or you could just cache all changes locally - inserts, updates and deletes - and then call Update once at the end to save all the changes together.
Add cmd.ExecuteNonQuery();
private void delet_button_Click(object sender, EventArgs e)
{
int i = dataGridView1.CurrentCell.RowIndex;
string strid = dataGridView1[0, i].Value.ToString();
//MessageBox.Show(strid);
int id = Convert.ToInt32(strid);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete from MessagesTable where [ID]=#ID ";
cmd.Parameters.AddWithValue("#ID", id);
cmd.ExecuteNonQuery();
MessageBox.Show("Message was deleted");
BindGrid();
}
Related
It is a simple insert, update, delete operation Application in C# I am working on and I am using Access 2010 database (Accdb). Insert and Update are working and data is properly populating in DataGridView but delete operation is glitch.
I run the app, previously stored records populated in DataGridView at Form load, I click on delete and selected row deleted from the database and datagridview populates to show updated data.
Now I select another row and click again on delete button but it doesn't delete any row.
ExecuteNonQuery return 0 this time and I debugged it. Cust_ID is the same which is selected on row click. Don't know what is happening here. Need a look from another person's perspective.
Here is code.
//Some Global Variables
int r;
int R_ID;
string cid = "";
string scon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\DB_Medical.accdb;Persist Security Info=True";
OleDbConnection con;
OleDbCommand cmd = new OleDbCommand();
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgv.SelectedRows.Count == 0)
{
MessageBox.Show("No row selected");
}
else
{
DeleteRecord();
}
}
public void DeleteRecord()
{
con = new OleDbConnection(scon);
con.Open();
cmd.Connection = con;
int id = int.Parse(dgv.Rows[dgv.SelectedRows[0].Index].Cells[0].Value.ToString());
string delquery = "DELETE FROM tbl_Customer WHERE Cust_ID=#id";
cmd.Parameters.AddWithValue("#id", id);
cmd.CommandText = delquery;
int row = cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(row + " rows deleted.");
LoadDataInGridView();
}
private void LoadDataInGridView()
{
string q1 = "SELECT * FROM tbl_Customer";
con = new OleDbConnection(scon);
con.Open();
cmd.Connection = con;
OleDbDataAdapter adapter = new OleDbDataAdapter(q1, con);
DataSet s1 = new DataSet();
adapter.Fill(s1);
dgv.DataSource = s1.Tables[0];
con.Close();
ViewAdjust();
}
private void ViewAdjust()
{
dgv.Columns[0].HeaderText = "ID";
dgv.Columns[1].HeaderText = "Name";
dgv.Columns[2].HeaderText = "Address";
dgv.Columns[3].HeaderText = "City";
dgv.Columns[4].HeaderText = "Mobile";
dgv.Columns[5].HeaderText = "Phone";
}
I'm fairly new to programming with c#.
So I have created database table Info with columns ID, PersonName, City, and binded it to DataGridView in WinForms. Whenever i change cell value or add a new cell, I want it to update/insert respectively into the db table. My question is which event I should you? I have tried CellEndEdit, CellValueChanged, CellLeave, and none seems to be working.
This is my INSERT Query:
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Info([PersonName], [City]) Values (#personName, #city)";
cmd.Parameters.AddWithValue("#personName", dataGridView1.SelectedCells[0].Value.ToString());
cmd.Parameters.AddWithValue("#city", dataGridView1.SelectedCells[0].Value.ToString());
cmd.ExecuteNonQuery();
dataGridView1.ResetBindings();
conn.Close();
And for the UPDATE Query
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
string updateQuery = "update Info set [PersonName]='" + dataGridView1.SelectedCells[0].Value + "', [City]='" + dataGridView1.SelectedCells[0].Value + "', where ID=" + dataGridView1.SelectedRows[0] + "";
cmd.CommandText = updateQuery;
cmd.ExecuteNonQuery();
conn.Close();
I'm aware that for CellLeave event it might not be getting the right cells, but have no idea as to why the other events aren't working.
Anyone want to share any t
You are using the right event but use it like below. SelectedCells may not return the right value. use the e.RowIndex which will return the value for exact Cell that you were editing.
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string Person = dataGridView1.Rows[e.RowIndex].Cells["Person"].Value.ToString();
string City = dataGridView1.Rows[e.RowIndex].Cells["City"].Value.ToString();
AddToDatabase(Person,City);
}
I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}
I am trying to delete selected data from datagrid and database at the same time when user clicks on "Delete". It is not working and error message shows that "Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"
Can anyone help me out this coding.
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
string strSqlConnection = #"Data Source = KK\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = JeanDB";
if ((dgvCustomerView.Rows.Count>0) && (dgvCustomerView.SelectedRows[1].Index != dgvCustomerView.Rows.Count))
{
SqlConnection sqlconn = new SqlConnection(strSqlConnection);
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);
sqlconn.Open();
DataTable dtEmployee = new DataTable("Customers");
sdaCustomer.Fill(dsCustomers, "Customers");
sqlconn.Close();
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
MessageBox.Show("Deleted Successfully");
}
}
Instead of Remove you can rebind grid:
dgvEmpView.DataSource = dsCustomers;
dgvEmpView.DataBind();
MessageBox.Show("Deleted Successfully");
and for deletion ExecuteNonQuery is used:
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
sqlconn.Open();
cmd.ExecuteNonQuery();
Unless you have two rows selected referencing the SelectedRows[1] is wrong. The array indexes start always with zero. (Probably it is just a type because the other lines references correctly the row to be deleted)
if ((dgvCustomerView.Rows.Count>0) &&
(dgvCustomerView.SelectedRows[0].Index != dgvCustomerView.Rows.Count))
{
....
but then, to delete the row in the database, you don't need to use an SqlDataAdapter.
You could work directly with a SqlCommand
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
cmd.Parameters.AddWithValue("#iCustomerID", iCustomerID);
sqlconn.Open();
cmd.ExecuteNonQuery();
finally you could simply remove the selected row from the grid without further query
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
If do not use sql parameters then use plain sql query.
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = "+ iCustomerID.ToString();
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);
I Have a gridview with just one column. I have written code like
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
string Users = GridView1.Rows[i].Cells[0].Text;
string strQuery = "insert into Table1 (FileName, DateTimeUploaded, Type, Username)" +
" values(#FileName, #DateTimeUploaded, #Type, #Username)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#FileName", datalink);
cmd.Parameters.AddWithValue("#Type", ext);
cmd.Parameters.AddWithValue("#DateTimeUploaded", DateTime.Now);
cmd.Parameters.AddWithValue("#Username", Users);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
con.Close();
con.Dispose();
}
If this gridview has 2 rows, then the first row is stored in database twice. If gridview has 3 rows then the first row is stored thrice. How can I solve this?
Explanation:
You are inserting your data into the database inside your GridView's RowDataBound event - this is executing every time a DataRow is being bound! This, along with the fact that you're looping accross every row each time using:
for (int i = 0; i < GridView1.Rows.Count; i++) { // inserting record from each row }
means your rows are going to be inserted more than once as more rows are bound. You need to remove your for loop, and use e.Row.Cells[0] instead to reference and insert just the currently bound row data.
string Users = e.Row.Cells[0].Text;
You probably also want to check for only DataRows so your operations don't occur on footer/header rows etc.
New Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
string Users = e.Row.Cells[0].Text; // current row being bound
string strQuery = "insert into Table1 (FileName, DateTimeUploaded, Type, Username)" +
" values(#FileName, #DateTimeUploaded, #Type, #Username)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#FileName", datalink);
cmd.Parameters.AddWithValue("#Type", ext);
cmd.Parameters.AddWithValue("#DateTimeUploaded", DateTime.Now);
cmd.Parameters.AddWithValue("#Username", Users);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
con.Dispose();
}
}