First row ignored by Data Grid View in C# Linq - c#

I have a program which basically creates, reads, edits, and delete from a linq database.
It does function well on different rows, however when I select the first row to delete it, it acts as if there is no ROW selected so it returns me a "Select Row" output warning.
In addition when I click modify on the first row, it always edits the row below it only. (The other rows are not affected)
This is the 'event update' code in the class :-
public int UpdateEvent(int selectedRow, string name, DateTime date, string eventType, string eventVenue)
{
EventTicketEntities database = new EventTicketEntities();
Event selected = database.Events.Where(x => x.EventId == selectedRow).FirstOrDefault(); //selected row will give the id of the row
if (selected == null)
{
return -1;
}
else
{
selected.EventName = name;
selected.EventDate = date;
selected.EventType = eventType;
selected.EventVenue = eventVenue;
return database.SaveChanges();
}
}
This is the code of the 'event delete' in the class:-
public int DeleteEvent(int selectedRow)
{
EventTicketEntities database = new EventTicketEntities();
Event eventDelete = database.Events.Where(x => x.EventId == selectedRow).FirstOrDefault();
database.Events.Remove(eventDelete); //We use this method to delete the particular customer
return database.SaveChanges(); //returns the affected rows ....
}
This is the code of the button of the form:-
private void btnModify_Click(object sender, EventArgs e)
{
if (SelectedRow != -1) //if not selected do nothing
{
if (MessageBox.Show("Are you sure?", "Modify", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)
{
EventBL eBL = new EventBL();
int result = eBL.UpdateEvent(SelectedRow, eventName.Text, calendar.Value, cmbEventType.SelectedValue.ToString(), cmbEventVenue.SelectedValue.ToString());
MessageBox.Show(result + " rows affected!" + SelectedRow);
dgvEvents.DataSource = eBL.GetEvents();
dgvEvents.Refresh();
}
}
else
{
EventBL eBL = new EventBL();
MessageBox.Show("Select Row first" + SelectedRow);
dgvEvents.DataSource = eBL.GetEvents();
dgvEvents.Refresh();
}
}
This is the code of the delete button:-
private void btnDelete_Click(object sender, EventArgs e)
{
if (SelectedRow != -1) //if not selected do nothing
{
if (MessageBox.Show("Are you sure?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)
{
EventBL eBL = new EventBL();
int result = eBL.DeleteEvent(SelectedRow);
MessageBox.Show(result + " rows affected!");
dgvEvents.DataSource = eBL.GetEvents();
SelectedRow = -1;
}
}
else
{
MessageBox.Show("Select Row first");
}
}
And this is the code of the event handler of data grid view:-
private void dgvEvents_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > 0)
{
SelectedRow = int.Parse(dgvEvents[0, e.RowIndex].Value.ToString());
}
}
Your help is much appreciated.
Take care-
HurpaDerpa

by the way، selected will always get a value it can't be null
So the condition
If (selected==null)
Will always be false
Because you assign .firstordefault

Related

How to detect empty space in datagridview and warn the screen if it is empty?

I want only 3 of the columns in my table in Datagridview1 not to be empty. I want it to warn the screen when there is an empty field.
I tried to make a mandatory field to be filled in the datagridview1 table
When I add other data to the data I pull from sql in Datagridview, I want it to warn the screen to be filled if there should be no empty space.
As you can see in the photo below, only those places should not be empty, and when I press save, it should detect when there is an empty space and give a warning to the screen.
give a warning if there is free space
private void btn_Save_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Select * from Envanter where BilgNo,VarlikSahibi,IP", baglanti);
cmd.Parameters.AddWithValue("BilgNo", dataGridView1);
cmd.Parameters.AddWithValue("VarlikSahibi", dataGridView1);
cmd.Parameters.AddWithValue("IP", dataGridView1);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
commandBuilder = new SqlCommandBuilder(da);
da.Update(tablo);
MessageBox.Show("Saved");
Envanter();
return;
/*
if (dataGridView1.Rows.Cells[1].Value == null | Convert.ToString(row.Cells[1].Value) | string.IsNullOrEmpty)
{
DialogResult dr = MessageBox.Show("pls no empty", "Warn!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return;
*/
}
}
If you are using plain C# model classes, you can rely on data annotations validation attributes.
If you are using DataTable as the model, you can validate the DataTable by setting column or row errors and check if the data table has errors.
You can also look over the rows or cells of DataGridView and set cell or row errors, with or without databinding.
Example - Validating Cells of DataGridView and show error on cells
private bool ValidateCell(DataGridViewCell cell)
{
//Validation rules for Column 1
if (cell.ColumnIndex == 1)
{
if (cell.Value == null ||
cell.Value == DBNull.Value ||
string.IsNullOrEmpty(cell.Value.ToString()))
{
cell.ErrorText = "Required";
return false;
}
else
{
cell.ErrorText = null;
return true;
}
}
//Other validations
return true;
}
private bool ValidateDataGridView(DataGridView dgv)
{
return dgv.Rows.Cast<DataGridViewRow>()
.Where(r => !r.IsNewRow)
.SelectMany(r => r.Cells.Cast<DataGridViewCell>())
.Select(c => ValidateCell(c)).ToList()
.All(x => x == true);
}
Then use above methods before saving the data:
private void SaveButton_Click(object sender, EventArgs e)
{
if (!ValidateDataGridView(dataGridView1))
{
MessageBox.Show("Please fix validation errors");
return;
}
//Save changes;
}
To show the errors on cells or rows of DataGridView, set ShowRowErrors and ShowCellErrors to true.
dataGridView1.DataSource = dt;
dataGridView1.ShowCellErrors = true;
Also, if you want to update the validations of the cells, after editing the cell:
private void DataGridView1_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
ValidateCell(dataGridView1[e.ColumnIndex, e.RowIndex]);
}
First Iterate over the dataset rows and then iterate over the value of each cell if there are any empty values return the message box of your choice to the user. Please find the below attached code for your reference.
You can do the following :
foreach (DataGridViewRow rw in this.dataGridView1.Rows)
{
for (int i = 0; i < rw.Cells.Count; i++)
{
if (rw.Cells[i].Value == null || rw.Cells[i].Value == DBNull.Value || String.IsNullOrWhiteSpace(rw.Cells[i].Value.ToString())
{
// here is your input message box...
string promptValue = Prompt.ShowDialog("Message", "some other string you want!");
}
else
{
// Proceed with the things you want to do..
}
}
}
And use the below code to create an input popup:
public static class Prompt
{
public static string ShowDialog(string text, string caption)
{
Form prompt = new Form()
{
Width = 500,
Height = 150,
FormBorderStyle = FormBorderStyle.FixedDialog,
Text = caption,
StartPosition = FormStartPosition.CenterScreen
};
Label textLabel = new Label() { Left = 50, Top=20, Text=text };
TextBox textBox = new TextBox() { Left = 50, Top=50, Width=400 };
Button confirmation = new Button() { Text = "Ok", Left=350, Width=100, Top=70, DialogResult = DialogResult.OK };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
}
}
And you can call it using :
string promptValue = Prompt.ShowDialog("Message", "some other string you want!");

Add value instead to datagridview if item already exist

Hi guys here is my problem. I have 2 datagridview.
What i want to do is whenever i click "add this datagridview1 row(product) to datagridview2" and that product from datagridview1 is already in datagridview2, it will just add the value of a textbox(quantity) to the quantity cell in datagridview2 which have same ID as the one being inserted.
It can already detect if the product your inserting to datagridview2 is already existing but i cant make it add the value of the textbox to the existing cell in the datagridview.
Here are my codes(that is wrong and not working) and pic of the datagridviews.
private bool alreadyincart()
{
foreach (DataGridViewRow row in dgvOrdercart.Rows)
{
int productcartID = Convert.ToInt32(dgvOrderproductlist.CurrentRow.Cells[0].Value.ToString());
if (Convert.ToInt32(row.Cells[0].Value) == productcartID)
{
MessageBox.Show("Item already exist, Adding the quantity instead.");
int textboxquantity = Convert.ToInt32(bakss.Text);
int dgvquantity = Convert.ToInt32(row.Cells[3].Value);
int dgvnewquantity;
dgvnewquantity = dgvquantity + textboxquantity;
dgvOrdercart.Rows[productcartID].Cells[3].Value = dgvnewquantity;
return false;
}
}
return true;
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (!validate())
{
return;
}
else if (!alreadyincart())
{
return;
}
else
{
addData(dgvOrderproductlist.CurrentRow.Cells[0].Value.ToString(),
dgvOrderproductlist.CurrentRow.Cells[1].Value.ToString(),
dgvOrderproductlist.CurrentRow.Cells[2].Value.ToString(),
bakss.Text, lblPrice.Text, totalprayss.Text, cboOrderSupplier.SelectedItem.ToString());
}
}
Try to change
dgvOrdercart.Rows[productcartID].Cells[3].Value = dgvnewquantity;
to
row.Cells[3].Value = dgvnewquantity;

Delete a row in DataGridView c# using textbox value

I have created a datagridview that gets all the data from MySQL Workbench database. Below this datagridview, I have created another datagrid with the same columns. For that, I have created a copy function, that on selecting the rows form the first datagridview, copies the selected rows to the second datgrid.
I have then created textboxes that displays the rows that are selected in the second datagridview.
All I want to do now is, get the values from the textboxes, match it in first datagridview, and after clicking on delete button, delete the respected row from first datagridview and respectievely from the database.
I am new to c#, so any help will be appreciated.
Source Code:
namespace panelApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void copy_Click(object sender, EventArgs e)
{
// dataGridView2.Rows.Clear(); (code used if you want to delete previous selections)
foreach (DataGridViewRow item in dataGridView1.Rows)
{
if (item.Selected == true)
{
int n = dataGridView2.Rows.Add();
dataGridView2.Rows[n].Cells[0].Value = item.Cells[0].Value.ToString();
dataGridView2.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString();
dataGridView2.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString();
}
}
}
public void fetch_Click(object sender, EventArgs e)
{
this.productsTableAdapter.Fill(this.productsDataset.products);
productsDataset dt = new productsDataset();
foreach (DataRow item in dt.products.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[1].Value = item["product_id"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["product_name"].ToString();
dataGridView1.Rows[n].Cells[3].Value = item["category_id"].ToString();
}
}
private void delete_btn_Click(object sender, EventArgs e)
{
try
{
if (dataGridView1.Rows.Cell[0].Text == TextBox1.tex) // error on this line.
{
}
}
catch (System.Exception)
{
MessageBox.Show("Not able to Delete");
}
}
private void dataGridView2_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView2.Rows[e.RowIndex];
product_idTxtbx.Text = row.Cells["product_id"].Value.ToString();
proName_txtbx.Text = row.Cells["product_name"].Value.ToString();
catID_txtbx.Text = row.Cells["category_id"].Value.ToString();
}
}
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView2.Rows[e.RowIndex];
product_idTxtbx.Text = row.Cells["product_id"].Value.ToString();
proName_txtbx.Text = row.Cells["product_name"].Value.ToString();
catID_txtbx.Text = row.Cells["category_id"].Value.ToString();
}
}
private void delete2_Click(object sender, EventArgs e)
{
// if (dataGridView1.Rows["row.index"].Cells["productidDG"].Value.ToString() == product_idTxtbx.Text)
{
}
}
}
}
On delete button click event btn_OnDelete() find the gridview index then find the all id's by row index.
Then compare each gridview row id to textbox item id
like:
if(GridView1.Rows.Cell[0].Text == TextBox1.tex)
{
// Delete Query here
}
for full solution share code with me.
see here demo link: CRUD Operation link
You should use this code:
<asp:Button ID="delete" runat="server" CommandArgument='<%#Eval("Id") %>' Text="Delete" />
private void delete_btn_Click(object sender, EventArgs e)
{
//incase you need the row index
int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;
int Prod_Id= Convert.ToInt32(e.CommandArgument);
//followed by your code
try
{
// Then Compare your Id here in this if condition
// if (dataGridView1.Rows.Cell[0].Text == TextBox1.tex
if (Prod_id == Convert.ToInt32(TextBox1.text)) // error on this line.
{
// User Code Here
}
}
catch (System.Exception)
{
MessageBox.Show("Not able to Delete");
}
}
please make your code like below
private void delete_btn_Click(object sender, EventArgs e)
{
try
{
foreach (GridViewRow row in dataGridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
if (row.Cell[0].value == TextBox1.tex)
{
//delete opration here for TextBox1.tex/row.Cell[0].Text(Product_id)
break;
}
}
}
}
catch (System.Exception)
{
MessageBox.Show("Not able to Delete");
}
}

Search for value in DataGridView in a column

I want the user to be able to search for a number in a column in the DataGridView (dgv). The dgv can hold many records. Each record has a Project Number. So I want the user to be able to search for a project number in column Project Number. The columns I have are: ProjectID(not visible); Image(no headertext); Project Number; Project Name; Company; Contact.
Here is my code:
private void btnSearch_Click(object sender, EventArgs e)
{
string searchValue = textBox1.Text;
int rowIndex = -1;
dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dgvProjects.Rows)
{
if (row.Cells[row.Index].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dgvProjects.Rows[row.Index].Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Problem #1: What it does so far: The user types the project number in TextBox1. When he/she clicks the button, the code searches for this string in the rows, and when found the project number, that row gets selected. It works fine, but only once. When I want to search for an other project number, nothing happens.
Problem #2: I think this can be done in a better way, by searching the values for column Project Name only. But how should I do this properly?
The code I used to search comes from this answer
Why you are using row.Cells[row.Index]. You need to specify index of column you want to search (Problem #2). For example, you need to change row.Cells[row.Index] to row.Cells[2] where 2 is index of your column:
private void btnSearch_Click(object sender, EventArgs e)
{
string searchValue = textBox1.Text;
dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dgvProjects.Rows)
{
if (row.Cells[2].Value.ToString().Equals(searchValue))
{
row.Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Why don't you build a DataTable first then assign it to the DataGridView as DataSource:
DataTable table4DataSource=new DataTable();
table4DataSource.Columns.Add("col00");
table4DataSource.Columns.Add("col01");
table4DataSource.Columns.Add("col02");
...
(add your rows, manually, in a circle or via a DataReader from a database table)
(assign the datasource)
dtGrdViewGrid.DataSource = table4DataSource;
and then use:
(dtGrdViewGrid.DataSource as DataTable).DefaultView.RowFilter = "col00 = '" + textBoxSearch.Text+ "'";
dtGrdViewGrid.Refresh();
You can even put this piece of code within your textbox_textchange event and your filtered values will be showing as you write.
It's better also to separate your logic in another method, or maybe in another class.
This method will help you retreive the DataGridViewCell object in which the text was found.
/// <summary>
/// Check if a given text exists in the given DataGridView at a given column index
/// </summary>
/// <param name="searchText"></param>
/// <param name="dataGridView"></param>
/// <param name="columnIndex"></param>
/// <returns>The cell in which the searchText was found</returns>
private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
{
DataGridViewCell cellWhereTextIsMet = null;
// For every row in the grid (obviously)
foreach (DataGridViewRow row in dataGridView.Rows)
{
// I did not test this case, but cell.Value is an object, and objects can be null
// So check if the cell is null before using .ToString()
if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
{
// the searchText is equals to the text in this cell.
cellWhereTextIsMet = row.Cells[columnIndex];
break;
}
}
return cellWhereTextIsMet;
}
private void button_click(object sender, EventArgs e)
{
DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
if (cell != null)
{
// Value exists in the grid
// you can do extra stuff on the cell
cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
}
else
{
// Value does not exist in the grid
}
}
// This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
string searchValue=textBoxSearch.Text;
int rowIndex = 1; //this one is depending on the position of cell or column
//string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
bool valueResulet = true;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dataGridView1.Rows[rowIndex].Selected = true;
rowIndex++;
valueResulet = false;
}
}
if (valueResulet != false)
{
MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
return;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Filter the data directly from DataTable or Dataset:
"MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
this.dataGridView1.DataSource = "MyTable".DefaultView;
Use this code on event KeyUp of Textbox, replace "MyTable" for you table name or dataset, replace for the field where you want make the search.
"MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'";
this.dataGridView1.DataSource = "MyTable".DefaultView;
How about the relation to the database connections and the Datatable? And how should i set the DefaultView correct?
I use this code to get the data out:
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();
DataTable dt = new DataTable();
adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
string searchValue = txtSearch.Text;
string colName = dataGridView1.Columns[1].Name;//Column Number of Search
((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format(colName+" like '%{0}%'", searchValue.Trim().Replace("'", "''"));
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
btnSearch_Click(null,null);
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
string searchValue = txtSearch.Text;
for (var i = 0; i <= dgvList.RowCount; i++)
{
for (var j = 0; j <= dgvList.ColumnCount; j++)
{
if ((dgvList.Item(j, i).FormattedValue.ToString.ToLower).ToString.Contains(searchValue.ToString.ToLower))
{
Console.Writeline("found");
dgvList.Item(j, i).Selected = true;
return;
}
}
}
}
This method will search all rows and cells in the DataGridView, If result is true then select the row.
I'm can solve it simply:
public static int SearchDGV(DataGridView dgv, string SearchValue, string ColName)
{
foreach (DataGridViewRow Row in dgv.Rows)
{
if (Row.Cells[ColName].Value.ToString().Equals(SearchValue))
return Row.Index;
}
return -1;
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
DataView dv = ds.Tables["todo"].DefaultView;
dv.RowFilter = "topic LIKE '" + textBox3.Text + "%'";
dataGridView1.DataSource = dv;
}

How to delete a selected DataGridViewRow and update a connected database table?

I have a DataGridView control on a Windows Forms application (written with C#).
What I need is: when a user selects a DataGridViewRow, and then clicks on a 'Delete' button, the row should be deleted and next, the database needs to be updated using table adapters.
This is what I have so far:
private void btnDelete_Click(object sender, EventArgs e)
{
if (this.dataGridView1.SelectedRows.Count > 0)
{
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
}
}
Furthermore, this only deletes one row. I would like it where the user can select multiple rows.
This code removes selected items of dataGridView1:
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
}
private void buttonRemove_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
Removes rows which indexes are in selected cells. So, select any cells, and their corresponding rows will be removed.
I have written the following code, please take a look:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
if (!row.IsNewRow) dataGridView1.Rows.Remove(row);
using the Index of the selected row still could work; see if the code below will do the trick:
int selectedCount = dataGridView1.SelectedRows.Count;
while (selectedCount > 0)
{
if (!dataGridView1.SelectedRows[0].IsNewRow)
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
selectedCount--;
}
I hope this helps, regards.
private void btnDelete_Click(object sender, EventArgs e)
{
if (e.ColumIndex == 10)// 10th column the button
{
dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
}
}
This solution can be delete a row (not selected, clicked row!) via "e" param.
maybe you can use temp list for delete. for ignore row index change
<pre>
private void btnDelete_Click(object sender, EventArgs e)
{
List<int> wantdel = new List<int>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((bool)row.Cells["Select"].Value == true)
wantdel.Add(row.Index);
}
wantdel.OrderByDescending(y => y).ToList().ForEach(x =>
{
dataGridView1.Rows.RemoveAt(x);
});
}
</pre>
To delete multiple rows in datagrid, c#
parts of my code:
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagrid1.SelectedRows)
{
//get key
int rowId = Convert.ToInt32(row.Cells[0].Value);
//avoid updating the last empty row in datagrid
if (rowId > 0)
{
//delete
aController.Delete(rowId);
//refresh datagrid
datagrid1.Rows.RemoveAt(row.Index);
}
}
}
public void Delete(int rowId)
{
var toBeDeleted = db.table1.First(c => c.Id == rowId);
db.table1.DeleteObject(toBeDeleted);
db.SaveChanges();
}
private: System::Void button9_Click(System::Object^ sender, System::EventArgs^ e)
{
String^ constring = L"datasource=localhost;port=3306;username=root;password=password";
MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
conDataBase->Open();
try
{
if (MessageBox::Show("Sure you wanna delete?", "Warning", MessageBoxButtons::YesNo) == System::Windows::Forms::DialogResult::Yes)
{
for each(DataGridViewCell^ oneCell in dataGridView1->SelectedCells)
{
if (oneCell->Selected) {
dataGridView1->Rows->RemoveAt(oneCell->RowIndex);
MySqlCommand^ cmdDataBase1 = gcnew MySqlCommand("Delete from Dinslaken_DB.Configuration where Memory='ORG 6400H'");
cmdDataBase1->ExecuteNonQuery();
//sda->Update(dbdataset);
}
}
}
}
catch (Exception^ex)
{
MessageBox::Show(ex->ToString());
}
}
Well, this is how I usually delete checked rows by the user from a DataGridView, if you are associating it with a DataTable from a Dataset (ex: DataGridView1.DataSource = Dataset1.Tables["x"]), then once you will make any updates (delete, insert,update) in the Dataset, it will automatically happen in your DataGridView.
if (MessageBox.Show("Are you sure you want to delete this record(s)", "confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
{
try
{
for (int i = dgv_Championnat.RowCount -1; i > -1; i--)
{
if (Convert.ToBoolean(dgv_Championnat.Rows[i].Cells[0].Value) == true)
{
Program.set.Tables["Champ"].Rows[i].Delete();
}
}
Program.command = new SqlCommandBuilder(Program.AdapterChampionnat);
if (Program.AdapterChampionnat.Update(Program.TableChampionnat) > 0)
{
MessageBox.Show("Well Deleted");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
have a look this way:
if (MessageBox.Show("Sure you wanna delete?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
bindingSource1.RemoveAt(item.Index);
}
adapter.Update(ds);
}
Try this:
if (dgv.SelectedRows.Count>0)
{
dgv.Rows.RemoveAt(dgv.CurrentRow.Index);
}
if(this.dgvpurchase.Rows.Count>1)
{
if(this.dgvpurchase.CurrentRow.Index<this.dgvpurchase.Rows.Count)
{
this.txtname.Text = this.dgvpurchase.CurrentRow.Cells[1].Value.ToString();
this.txttype.Text = this.dgvpurchase.CurrentRow.Cells[2].Value.ToString();
this.cbxcode.Text = this.dgvpurchase.CurrentRow.Cells[3].Value.ToString();
this.cbxcompany.Text = this.dgvpurchase.CurrentRow.Cells[4].Value.ToString();
this.dtppurchase.Value = Convert.ToDateTime(this.dgvpurchase.CurrentRow.Cells[5].Value);
this.txtprice.Text = this.dgvpurchase.CurrentRow.Cells[6].Value.ToString();
this.txtqty.Text = this.dgvpurchase.CurrentRow.Cells[7].Value.ToString();
this.txttotal.Text = this.dgvpurchase.CurrentRow.Cells[8].Value.ToString();
this.dgvpurchase.Rows.RemoveAt(this.dgvpurchase.CurrentRow.Index);
refreshid();
}
}
You delete first from the database and then you update your datagridview:
//let's suppose delete(id) is a method which will delete a row from the database and
// returns true when it is done
int id = 0;
//we suppose that the first column in the datagridview is the ID of the ROW :
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
id = Convert.ToInt32(row.Cells[0].Value.ToString());
if(delete(id))
this.dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
//else show message error!
private void btnDelete_Click(object sender, EventArgs e)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
?BindingSource.EndEdit();
?TableAdapter.Update(this.?DataSet.yourTableName);
}
//NOTE:
//? - is your data from database
Exception no need ... or change with your own code.
CODE:
DB:
Example: prntscr.com/p3208c
DB Set: http://prntscr.com/p321pw
ArrayList bkgrefs = new ArrayList();
foreach (GridViewRow rowd in grdOptionExtraDetails.Rows)
{
CheckBox cbf = (CheckBox)rowd.Cells[1].FindControl("chkbulk");
if (cbf.Checked)
{
rowd.Visible = true;
bkgrefs.Add(Convert.ToString(grdOptionExtraDetails.Data.Rows[rowd.RowIndex]["OptionID"]));
}
else
{
grdOptionExtraDetails.Data.Rows.RemoveAt(rowd.DataItemIndex);
rowd.Visible = false;
}
}
Try this:
foreach (DataGridViewRow item in this.YourGridViewName.SelectedRows)
{
string ConnectionString = (#"Data Source=DESKTOPQJ1JHRG\SQLEXPRESS;Initial Catalog=smart_movers;Integrated Security=True");
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM TableName WHERE ColumnName =#Index", conn);
cmd.Parameters.AddWithValue("#Index", item.Index);
int i = cmd.ExecuteNonQuery();
if (i != 0)
{
YourGridViewName.Rows.RemoveAt(item.Index);
MessageBox.Show("Deleted Succefull!", "Great", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
MessageBox.Show("Deleted Failed!", "Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This worked for me :
private void btnRemove_Click(object sender, EventArgs e) {
int count = dgvSchedule.SelectedRows.Count;
while (count != 0) {
dgvSchedule.Rows.RemoveAt(dgvSchedule.SelectedRows[0].Index);
count--;
}
}
this command delete selected row when user selected in datagridview:
gvTest.Rows.RemoveAt(dvTest.CurrentRow.Index];
for (int j = dataGridView1.Rows.Count; j > 0 ; j--)
{
if (dataGridView1.Rows[j-1].Selected)
dataGridView1.Rows.RemoveAt(j-1);
}
It Work for me !
private: System::Void MyButton_Delete_Click(System::Object^ sender, System::EventArgs^ e) {
// Удалить столбец(Row).
MydataGridView->Rows->RemoveAt(MydataGridView->CurrentCell->RowIndex);
}
here is one very simple example:
ASPX:
<asp:GridView ID="gvTest" runat="server" SelectedRowStyle-BackColor="#996633"
SelectedRowStyle-ForeColor="Fuchsia">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdateClick"/>
Code Behind:
public partial class _Default : System.Web.UI.Page
{
private readonly DataTable _dataTable;
public _Default()
{
_dataTable = new DataTable();
_dataTable.Columns.Add("Serial", typeof (int));
_dataTable.Columns.Add("Data", typeof (string));
for (var i = 0; ++i <= 15;)
_dataTable.Rows.Add(new object[] {i, "This is row " + i});
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
private void BindData()
{
gvTest.DataSource = _dataTable;
gvTest.DataBind();
}
protected void btnUpdateClick(object sender, EventArgs e)
{
if (gvTest.SelectedIndex < 0) return;
var r = gvTest.SelectedRow;
var i = r.DataItemIndex;
//you can get primary key or anyother column vlaue by
//accessing r.Cells collection, but for this simple case
//we will use index of selected row in database.
_dataTable.Rows.RemoveAt(i);
//rebind with data
BindData();
//clear selection from grid
gvTest.SelectedIndex = -1;
}
}
you will have to use checkboxes or some other mechanism to allow users to select multiple rows and then you can browse the rows for ones with the checkbox checked and then remove those rows.

Categories

Resources