Deleting from .net gridview - c#

Im looking to programmatically delete from a GridView.
I have implemented the gridview's OnRowDeleting="Delete_Record" event handler, and this is called when the user clicks the delete link on the GridView, but as the row doesn't seem to be selected the code which does the delete does not work.
To test further I can click select, to select the row (commenting out the code behind the select) then if I click delete the code runs fine.
Is there a way to have the row selected as the first step in the Delete_Record?
GridViewRow row = gvResults.SelectedRow;
string id = row.Cells[1].Text;
ASB_DataDataContext db = new ASB_DataDataContext();
var delCase = from dc in db.Inputts
where dc.counter == Convert.ToInt32(id)
select dc;
foreach (var nCase in delCase)
{
db.Inputts.DeleteOnSubmit(nCase);
db.SubmitChanges();
}

Since you are using the event you should be having the required index as part of the GridViewDeleteEventArgs e which should be like say e.RowIndex
you can then access your needed parameter as grid.Rows[e.RowIndex].Cells[1].Text

You can achieve by the code shown below
public void GridView1_Delete_Record (Object sender, GridViewDeleteEventArgs e)
{
string id = gridView1.Rows[e.RowIndex].Cells[2].Text;
ASB_DataDataContext db = new ASB_DataDataContext();
var delCase = from dc in db.Inputts
where dc.counter == Convert.ToInt32(id)
select dc;
foreach (var nCase in delCase)
{
db.Inputts.DeleteOnSubmit(nCase);
db.SubmitChanges();
} Message.Text = "";
}

Set db.Inputts as DataSource of your datagrid. Just add next two lines after your code:
datagridView1.DataSource = null;
datagridView1.DataSource = db.Inputts;
Setting datasource to null is for clearing previous data from datagrid;

Related

remove default row selection datagridview

I have a datagridview that when it loaded first row is selected. I want to delete a record but I don't want first row select. I want message to user that first select a row then click delete button. I try these code but they don't worked.
//kharidDataGridView.Rows[0].Selected = false;
//kharidDataGridView.ClearSelection();
//kharidDataGridView.CurrentCell = null;
I use below codes in WPF:
object item = datagrideview1.SelectedItem;
if (item == null)
{
//message to user
}
thank you
You can remove default selected row by handling data-grid loaded event
private void datagrideview1_Loaded(object sender, RoutedEventArgs e)
{
datagrideview1.SelectedIndex = -1;
}

C# How do I copy from one data grid to another without overwriting my previous selection?

I have 2 datagrid views with one datatable. I am trying to have a button that when clicked it adds the rows from csv_datagridview to optimal_datagridview. The below works however whenever I deselect an entry in csv_datagridview and hit the button again it clears that selection. I would like to have the selection stick each time.
if (selectedRowCount <= 9)
{
List<object> destList = new List<object>();
foreach (DataGridViewRow row in csv_datagridview.SelectedRows)
destList.Add(row.DataBoundItem);
optimaldataGridView.DataSource = destList;
Thank you so much in advance :)
It is unclear what your exact problem is with the little code you show, but from your statement whenever I deselect an entry in csv_datagridview and hit the button again it clears that selection. I am guessing that if nothing is selected, the data in optimaldataGridView clears when you press the add selected button.
I will assume the csv_datagridview is bound to a table. Your posted code shows the creation of new List destList which you fill with the selected rows from the csv_datagridview. Then you set optimaldataGridView data source to the destList. One issue I see in this picture is that as soon as you leave the if (selectedRowCount <= 9) clause… destList will no longer exist. As a data source for a DataGridView on your form, I would think you would want to keep this List global as long as the form is open. Either way... you are not adding the selected rows, you are simply removing the existing rows and then adding what was selected in csv_datagridview.
I hope the code below will help. I created two DataTables, one for each DataGridView. The csv_datagridview data table is filled with some data, the second data table is left empty. Then simply add the selected rows from the csv_datagridview to the optimaldataGridView’s DataTable… Then refresh optimaldataGridView.
DataTable table1;
DataTable table2;
public Form1() {
InitializeComponent();
csv_datagridview.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
optimaldataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
table1 = GetTable("table1");
table2 = GetTable("table2");
FillTable(table1);
csv_datagridview.DataSource = table1;
optimaldataGridView.DataSource = table2;
}
private void button1_Click(object sender, EventArgs e) {
if (csv_datagridview.SelectedRows.Count > 0) {
foreach (DataGridViewRow row in csv_datagridview.SelectedRows) {
DataRowView dr = (DataRowView)row.DataBoundItem;
table2.Rows.Add(dr.Row.ItemArray[0], dr.Row.ItemArray[1], dr.Row.ItemArray[2]);
}
optimaldataGridView.Refresh();
}
}
private DataTable GetTable(string name) {
DataTable table = new DataTable(name);
table.Columns.Add("col1");
table.Columns.Add("col2");
table.Columns.Add("col3");
return table;
}
private void FillTable(DataTable table) {
for (int i = 0; i < 10; i++) {
table.Rows.Add("R" + i + "C0", "R" + i + "C1", "R" + i + "C2");
}
}
Hope this helps.
Your code is working on my side.
Created a DataTable for Datasource of csv_datagridview.
Selected some rows in this grid.
Clicked the button to copy the selected rows to the
optimaldataGridView
The selected rows are still selected.
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.ReadXml(Application.StartupPath + #"\test.xml");
csv_datagridview.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
csv_datagridview.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
List<object> destList = new List<object>();
foreach (DataGridViewRow row in csv_datagridview.SelectedRows)
destList.Add(row.DataBoundItem);
optimaldataGridView.DataSource = destList;
}
Make sure you have no events attached to the grids that may affect the selection.

Template checkbox checked property is getting false in Gridview for delete operation

I have used template CheckBox in gridview for multiple rows deletion, when I select multiple rows by selecting the CheckBox and perform the delete operation it seems to be selected CheckBox is not returning true on the code below.
protected void Button6_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
LinkButton ch = new LinkButton();
ch = (LinkButton)row.FindControl("l1");
id = Convert.ToInt16(ch.CommandArgument);
CheckBox chs = new CheckBox();
chs = ((CheckBox)row.FindControl("c1"));
if (chs.Checked == true)
{
DeleteSelected(id);
}
}
}
private void DeleteSelected(short id)
{
var ch = from a in empd.Employees where (a.ID == id) select a;
empd.Employees.DeleteAllOnSubmit(ch);
empd.SubmitChanges();
display_emp();
}
Could someone please assist me why CheckBox is not returning true value in calling function.
Well now I have fixed the connection everything, please just refresh the database.Please get the web application in the below link.
http://www.ziddu.com/download/20716096/WebApplication.zip.html
Please help me on why selected checkbox are not returning true in the code.
Details: Add if(IsPostback) at the start otherwise it just resets your grid controls. Example below
Solution:
if (!IsPostBack)
{
empd = new Employee_DetailsDataContext();
empd.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["DemosConnectionString1"].ConnectionString;
display_emp();
}

Move item from listbox1 to listbox2 in web application

I have 2 listboxes. One contains all the department which are unassigned and other listbox contains all the department which is assigned to a particular person. Now I want to add and delete departments using insert and delete query. The query will be performed on 1 table only ie Assigned Department(listbox2) and by clicking the SAVE button. I have done the insert part but unable to handle the delete part. I have seen few examples but they dont have DB event in them.
protected void Save_Click(object sender, EventArgs e)
{
DataTable dt = GetData2();
bool found = false;
foreach (RadListBoxItem item in RadListBox2.Items)
{
found = false;
foreach (DataRow dr in dt.Rows)
{
if (String.Compare(item.Value, dr["DeptID"].ToString()) == 0)
{
found = true;
label1.Text = "Add a New Group to the ListBox";
}
}
if (found == false)
{
Item(item.Text, item.Value);
}
This is what I am trying to do. I want to handle insert and delete event on Save button.
I figured out the solution so I am posting it in here.
foreach (DataRow dr in dt.Rows)
{
found = false;
foreach (RadListBoxItem item in RadListBox2.Items)
{
if (String.Compare(item.Value, dr["DeptID"].ToString()) == 0)
{
found = true;
}
}
if (found == false)
{
//delete here
}
}
}
I use the RadListBox's Transferred event. When the Transferred event fires Items look at the destination listbox's id and determine if the items were moved to the unassigned or assigned ListBox. Once you know the destination you can execute a query to add or remove rows from your database.
In any case, your Query will be dependent on your schema. In my situation I had a lookup table that determined if the item was attached.
rlistAvailable_Transferred(object sender, Telerik.Web.UI.RadListBoxTransferredEventArgs e)
{
if (e.DestinationListBox.ID == "rlistAttached")
{
foreach (Telerik.Web.UI.RadListBoxItem li in e.Items)
{
//do insert query using li.Value
}
}
else
{
foreach (Telerik.Web.UI.RadListBoxItem li in e.Items)
{
//do delete query using li.Value
}
}
}

Datarepeater delete only deleting top record

I have a datarepeater and the following code ONLY deletes the FIRST record regardless of which one is selected. I am not entirely convinced this is the correct way to do it with a datarepeater but I could not find a better solution. I need to be able to select any record and delete it.
//delete document
private void cmdDeleteDoc_Click(object sender, EventArgs e)
{
if (this.dataRepeater1.CurrentItemIndex == 0)
{
//begin reset
this.dataRepeater1.BeginResetItemTemplate();
// Delete Row Here
DataClasses1DataContext db = new DataClasses1DataContext();
System.Data.DataRowView SelectedRowView;
newCityCollectionDataSet.DocumentsRow SelectedRow;
SelectedRowView = (System.Data.DataRowView)documentsBindingSource.Current;
SelectedRow = (newCityCollectionDataSet.DocumentsRow)SelectedRowView.Row;
var matchedDocument = (from c in db.GetTable<Document>()
where c.DocIDKey == SelectedRow.DocIDKey
select c).SingleOrDefault();
db.Documents.DeleteOnSubmit(matchedDocument);
db.SubmitChanges();
LoadCaseNumberKey(matchedDocument.CaseNumberKey, false, "documents");
this.dataRepeater1.EndResetItemTemplate();
}
}
Any help would be great!.
My guess is that your are mixed up between your documentsBindingSource and your dataRepeater.
What you "see" visually is the dataRepeater, while what you "get", is the documentsBindingSource.Current (that you retrieve as being SelectedRowView) which is always set to 0 index. This is an all-too-common Winforms control trap.

Categories

Resources