Get multiple row DataKeys from gridview - asp.net

Currently I have a Button Click event which takes the DataKey from a row in a Datagrid (via a checkbox) and assigns it to an INT variable to Update an Individual in a databsse. Everything works fine when I only check 1 checkbox and run the Update. However I need the User to have the option to select all checkboxes and take all those Datakeys and assign it to the same variable
INT oNewParentID
Like I said evrything works fine when only 1 checkbox is Selected. I guess I'm asking how to get an Uknoiwn amount of Datakeys or all DataKeys selected by all Checkboxes and store them in the Variable above to run the Update for all Individuals Selected. Here is my Button Click Event so far which is working for 1 checkbox selected:
protected void imgbtnReassgin_Click(object sender, ImageClickEventArgs e)
{
foreach (GridViewRow row in gvSalesmanCustomers.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkSalesCustSelector");
if (cb != null && cb.Checked)
{
int oIndividualID = Convert.ToInt32((gvSalesmanCustomers.DataKeys[row.RowIndex].Value));
foreach (GridViewRow r in gvSalesmanByManager.Rows)
{
CheckBox chkBox = (CheckBox)r.FindControl("chkManagerSalesSelector");
if (chkBox != null && chkBox.Checked)
{
int oNewParentID = Convert.ToInt32((gvSalesmanByManager.DataKeys[r.RowIndex].Value));
Individual ind = new Individual();
ind.ReassignIndividual(oIndividualID, oNewParentID);
chkBox.Checked = false;
cb.Checked = false;
}
}
}
}
}
And her is my Update Stored Procedure :
CREATE DEFINER=`root`#`%` PROCEDURE `reassign_Individual`(
IN oIndividualID int(11),
IN oNewParentID int(11)
)
BEGIN
Update intelliair.individual
set ParentID = oNewParentID
Where IndividualID = oIndividualID;END

Re-organized code.
Added break to second foreach assuming that there's no reason to ReasignInvidual multiple times just to assign it to the last selected manager.
protected void imgbtnReassgin_Click(object sender, ImageClickEventArgs e)
{
List<int> ids = new List<int>();
foreach (GridViewRow row in gvSalesmanCustomers.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkSalesCustSelector");
if (cb != null && cb.Checked)
{
int oIndividualID = Convert.ToInt32((gvSalesmanCustomers.DataKeys[row.RowIndex].Value));
ids.Add(oIndividualID);
cb.Checked = false;
}
}
int oNewParentID = 0;
foreach (GridViewRow r in gvSalesmanByManager.Rows)
{
CheckBox chkBox = (CheckBox)r.FindControl("chkManagerSalesSelector");
if (chkBox != null && chkBox.Checked)
{
oNewParentID = Convert.ToInt32((gvSalesmanByManager.DataKeys[r.RowIndex].Value));
chkBox.Checked = false;
break; //no reason to go with the same logic to next records
//if you want to uncheck all the checkboxes continue with specific code just for that purpose
}
}
if (ids.Count > 0 && oNewParentID > 0)
foreach(var id in ids)
{
Individual ind = new Individual();
ind.ReassignIndividual(id, oNewParentID);
}
}

Related

Selected a row in a grid view, now want to update that record with update button click

I have been stuck on this and tried a few different things to use the update button to update the record that I selected from the grid view. I have 2 columns in the table Id and Name. I select the record and it populates a text box with the name.... this works fine. I just need to take that same record and update the name from that same text box after it is pulled into the text box by using an update button click event. I have two other buttons that work just fine which are "Add" and "Delete" and I will add that code as well but here is the code:
This is how I have populated the grid view on page load or when I call the method:
private void PopulateCompanyListGrid() //This will populate the grid with the table data on page load
{
IList<Company> companies;
using (var context = new IMSDBContext())
{
companies = context.Companies.ToList();
}
grdvwCompanyList.DataSource = companies;
grdvwCompanyList.DataBind();
}
This is how the grid view is set up:
<asp:GridView runat="server" ID="grdvwCompanyList" OnSelectedIndexChanged="SelectGridRow" DataKeyNames="Id, Name" AllowSorting="True" AutoGenerateSelectButton="True"></asp:GridView>
This is how I put the selected record in the text box:
public void SelectGridRow(object sender, EventArgs e) //This will populate the textbo with the row selected from the gridview
{
GridViewRow name = grdvwCompanyList.SelectedRow;
if (name != null)
{
var dataKey = grdvwCompanyList.DataKeys[name.RowIndex];
if (dataKey != null)
txtCompanyName.Text = (string)dataKey["Name"];
}
}
This is how I am adding records:
protected void btnAdd_Click(object sender, EventArgs e) // This method adds a record to the database
{
if (btnAdd.Text == "Add") // Clears the textbox and notification label and calls method to change name of button if the button says "Add"
{
txtCompanyName.Text = "";
lblCompanyNameNotification.Text = "";
ButtonChangeAddToSave();
}
else if (btnAdd.Text == "Save") // Checks if the button says "Save" and compares textbox and database for a matching record
{
IMSDBContext context = new IMSDBContext();
Company CompanyCheck = context.Companies.SingleOrDefault(Company => Company.Name == txtCompanyName.Text);
if (CompanyCheck != null) // Displays a notification if there is already a matching record
{
lblCompanyNameNotification.Text = "There is already a Company with that name.";
}
else if(txtCompanyName.Text == null)
{
lblCompanyNameNotification.Text = "Please enter a name of a company";
}
else if (txtCompanyName.Text != null) // Write the record to the database if no matching record in the database
{
Company n = new Company();
n.Name = txtCompanyName.Text.ToString();
context.Companies.Add(n);
context.SaveChanges();
txtCompanyName.Text = "";
lblCompanyNameNotification.Text = "";
ButtonChangeSaveToAdd();
}
}
PopulateCompanyListGrid(); // Calls method to repopulate the gridview
}
Add a hidden field in the markup to hold company Id:
<asp:HiddenField ID="hdnCompanyId" runat="server" ></asp:HiddenField>
In the selectGridRow method populate the hidden field with company Id:
public void SelectGridRow(object sender, EventArgs e) //This will populate the textbo with the row selected from the gridview
{
GridViewRow name = grdvwCompanyList.SelectedRow;
if (name != null)
{
var dataKeys = grdvwCompanyList.DataKeys[name.RowIndex];
if (dataKeys["Name"] != null)
txtCompanyName.Text = (string)dataKeys["Name"];
if (dataKeys["Id"] != null)
hdnCompanyId.Value = dataKeys["Id"].ToString();
}
}
In the btnUpdate_Click method get the company by Id and update it :
protected void btnUpdate_Click(object sender, EventArgs e)
{
int companyId;
string companyName = txtCompanyName.Text;
if(int.TryParse(hdnCompanyId.Value, out companyId)){
IMSDBContext context = new IMSDBContext();
Company company = context.Companies.SingleOrDefault(Company => Company.Id == companyId);
if (company != null && txtCompanyName.Text != "")
{
company.Name = companyName;
context.SaveChanges();
}
else
{
lblCompanyNameNotification.Text = "The Company does not exist.";
}
}
PopulateCompanyListGrid(); // Calls method to repopulate the gridview
}

Get value of rows when it s checkbox is checked in radgrid

I have a radgride with checkbox in each rows.I want when i click on button,it checks id of each rows that checked,put into the variable..
I know this code for gridview but I do not know equivalent of this code for radgrid
foreach (GridViewRow rw in grid1.Rows)
{
CheckBox chkBx = (CheckBox)rw.FindControl("Check");
if (chkBx != null && chkBx.Checked)
{
id= grid1.Rows[0].Cells[3].Text.ToString();
}
}
if (RadGrid1.Items.Count > 0)
{
foreach (GridDataItem item in RadGrid1.Items)//loops through each grid row
{
CheckBox chkBx = (CheckBox)rw.FindControl("Check");
if (chkBx != null && chkBx.Checked)
{
//string v= item["ColumnUniqueName"].Text;
string v= item.Cells[3].Text; //accessing cell using its ColumnUniqueName
}
}
}
For more information on Radgrid rows and cell access, check http://www.telerik.com/help/aspnet-ajax/grid-accessing-cells-and-rows.html
Try this: http://www.telerik.com/community/forums/aspnet-ajax/grid/loop-through-radgrid.aspx
foreach(GridItem rw in grid1.Items)
{
CheckBox chkBx = rw.FindControl("Check") as CheckBox ;
if (chkBx != null && chkBx.Checked)
{
string id = rw.Cells[3].Text;
}
}

How to find child gridview in user defined function

This is my code to save the selected check box values while paging, but as I am working with nested gridview I am unable to find the control of the required child gridview
private void SaveCheckedValues()
{
ArrayList userdetails = new ArrayList();
int index = -1;
GridView gv = (GridView)gvCustomers.FindControl("gvOrders"); // Is this correct or any other way of finding the child control
foreach (GridViewRow gvrow in gv.Rows)
{
index = (int)gv.DataKeys[gvrow.RowIndex].Value;
bool result = ((CheckBox)gvrow.FindControl("chkBoxChild")).Checked;
// Check in the Session
if (Session["CHECKED_ITEMS"] != null)
userdetails = (ArrayList)Session["CHECKED_ITEMS"];
if (result)
{
if (!userdetails.Contains(index))
userdetails.Add(index);
}
else
userdetails.Remove(index);
}
if (userdetails != null && userdetails.Count > 0)
Session["CHECKED_ITEMS"] = userdetails;
}
I have a generic recursive find control code that often helps in these circumstances. The issue with grid controls is that there is a certain level of nesting of controls int hem for the row and cell, and contents in the cell.
Private Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control
If root.ClientID Is Nothing AndAlso root.ClientID.EndsWith(id) Then
Return root
End If
For Each c As Control In root.Controls
Dim t As Control = FindControlRecursive(c, id)
If Not t Is Nothing Then
Return t
End If
Next c
Return Nothing
End Function
The code is in VB.net but you get the gist
private void SaveCheckedValues()
{
ArrayList userdetails = new ArrayList();
int index = -1;
foreach (GridViewRow gvRow1 in gvCustomers.Rows)
{
GridView gv = (GridView)gvRow1.FindControl("gvOrders");
foreach (GridViewRow gvrow in gv.Rows)
{
index = (int)gv.DataKeys[gvrow.RowIndex].Value;
bool result = ((CheckBox)gvrow.FindControl("chkBoxChild")).Checked;
// Check in the Session
if (Session["CHECKED_ITEMS"] != null)
userdetails = (ArrayList)Session["CHECKED_ITEMS"];
if (result)
{
if (!userdetails.Contains(index))
userdetails.Add(index);
}
else
userdetails.Remove(index);
}
}
if (userdetails != null && userdetails.Count > 0)
Session["CHECKED_ITEMS"] = userdetails;
}
try this:
private void SaveCheckedValues()
{
foreach(GridViewRow rIndex in GridView1.Rows)
{
GridView gv = new GridView();
gv = (GridView)row.FindControl("GridView2");
//user gv
}
}

Trying to Call an Update method in Button Click event

I am looping 2 Datagrids and getting the IndividualID's (PrimaryKeys) of the person(s) that are selected. I have debugged this and the loops are working fine. Howver when I call my Update Method from my Table Adapter, nothing seems to happen. It does not update. Here is my code. Not sure what I'm doing wrong:
protected void imgbtnReassgin_Click(object sender, ImageClickEventArgs e)
{
foreach (GridViewRow row in gvAdminCustomer.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkitemSelectorCustomers");
if (cb != null && cb.Checked)
{
int oIndividualID = Convert.ToInt32((gvAdminCustomer.DataKeys[row.RowIndex].Value));
// GlobalVar.oIndividualID = oIndividualID;
foreach (GridViewRow r in gvReassignCustomers.Rows)
{
CheckBox chkBox = (CheckBox)row.FindControl("chkitemSelectorAllManagersandSalesman");
if (chkBox != null && chkBox.Checked)
{
int oNewParentID = Convert.ToInt32((gvReassignCustomers.DataKeys[r.RowIndex].Value));
individualTableAdapter ind = new individualTableAdapter();
//Individual ind = new Individual();
ind.reassign_Individual(oIndividualID, oNewParentID);
}
}
gvAdminCustomer.DataBind();
}
}
}
Is it updating the database record and not reflecting on the grid? If that is the case, then it looks like it is just rebinding the grid with the datasource it used prior to the loop. You'll need to refresh your dataset and then rebind:
gvAdminCustomer.DataSource = YourDataSource;
gvAdminCustomer.DataBind();
Good Luck!

gridview column delete

Is there any other way to delete gridview column except using index..
I am using gridview with multiple checkbox.
I want to delete all those column whose checkboxes are checked..
I am retriving checkboxes as..
protected void ButtonApprove_Click(object sender, EventArgs e)
{
StringCollection sc = new StringCollection();
string id = string.Empty;
for (int i = 0; i < GridView1.Rows.Count; i++)//loop the GridView Rows
{
//find the CheckBox
CheckBox cb =
(CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
if (cb != null)
{
if (cb.Checked)
{
// get the id of the field to be deleted
id = GridView1.Rows[i].Cells[1].Text;
// add the id to be deleted in the StringCollection
sc.Add(id);
}
}
}
UpdateRecords(sc);
}
Please go through the Link for deleting multiple items
Check this to move the selected to another gridivew Move

Resources