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
Related
I am trying to delete selected rows from gridview in button click event but I am getting the below error:
Collection was modified; enumeration operation might not execute.
Code:
protected void btnRemoveUser_Click(object sender, EventArgs e)
{
DataTable yourDataTable = GetDataTable(Studentlist);
//CheckBox chkbx;
foreach(GridViewRow oneRow in Studentlist.Rows)
{
CheckBox chkbx = (CheckBox)oneRow.FindControl("ckbxID");
foreach (DataRow rowDT in yourDataTable.Rows) **//In this line throwing the exception**
{
if (chkbx.Checked == true)
{
yourDataTable.Rows.Remove(rowDT);
}
}
}
Studentlist.DataSource = yourDataTable;
Studentlist.DataBind();
}
Note: Studentlist is the gridview ID.
You can not remove item from collection while performing foreach on it for details visit this.
For now you can use easy technique to delete items.
for(int i = 0; i< yourDataTable.Rows.Count; i++)
{
if (chkbx.Checked == true)
{
yourDataTable.Rows.RemoveAt(i);
}
}
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
}
In my project I've got a variable numtorust which represents the number of the toursits.
(for testing purposes numtourist = 2)
for (i=0,numtoursut; i++)
I create dynamically 5 checkboxes with assigned checkedChanged event for each of tourist. Also to keep track which checkbox to which tourist applies I add attribute 'collection'
mycheckbox.InputAttributes.Add("collection", i.ToString());
In checkedchanged event handler - when a user selects a checkbox I checked if its collection attribute is = 0 or 1 (first or second user). then I add checkbox value to myche1 which is of type List<string) if collection attribute = 1.
But I when I decided to make one array of type List<string> with name Toursit
when I try to add an element to it I got an exception - Object reference not set to an instance of object in this row of my code
Toursist[Int32.Parse(chk.InputAttributes["collection"])].Add(chk.InputAttributes["value"].ToString());
Here is my full code
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
/*that doesn't work
if (chk.Checked)
{
Toursist[Int32.Parse(chk.InputAttributes["collection"])].Add(chk.InputAttributes["value"].ToString());
((List<String>[])Session["chk"])[Int32.Parse(chk.InputAttributes["collection"])] = Toursist[Int32.Parse(chk.InputAttributes["collection"])];
}*/
//this works with myche1 of type list<string>
if ((chk.Checked)&&(chk.InputAttributes["collection"].Equals("1")))
{
myche1.Add(chk.InputAttributes["value"].ToString());
lblProba.Text += chk.InputAttributes["value"].ToString();
Session["chk1"] = myche1;
}
}
edit 1:
teh new code of
protected void checkChanged(object sender, EventArgs e)
{
List<string>[] Toursist = new List<string>[2];
//Session["chk"] = new List<string>[2];
for (int i = 0; i < Toursist.Length; i++)
{
Toursist[i] = new List<string>();
// ((List<String>[])Session["chk"])[i] = Toursist[i];
}
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
if (((List<String>[])Session["chk"])[Int32.Parse(chk.InputAttributes["collection"])] == null)
{
((List<String>[])Session["chk"])[Int32.Parse(chk.InputAttributes["collection"])] = Toursist[Int32.Parse(chk.InputAttributes["collection"])];
}
Toursist[Int32.Parse(chk.InputAttributes["collection"])].Add(chk.InputAttributes["value"].ToString());
lblProba.Text += chk.InputAttributes["collection"].ToString();
((List<String>[])Session["chk"])[Int32.Parse(chk.InputAttributes["collection"])] = Toursist[Int32.Parse(chk.InputAttributes["collection"])];
}
again the same mistake this time when I test if Sessio["chk"] == 0.
but If I uncomment (so I no more have this mistake)
// ((List<String>[])Session["chk"])[i] = Toursist[i];
on each postback event my session will be empty and I don't want!!
You haven't created any lists. When you create an array of lists, it won't automatically create all the lists in the array, you have to do that manually:
List<string>[] Toursist = new List<string>[numtoursut];
for (int i = 0; i < Toursist.Length; i++) {
Toursist[i] = new List<string>();
}
I have a GridView which is binded with DataTable for the datasource, when there is no records in the underlying datasource i show up the EmptyDataTemplate with Two DropDown (State and City) and based on the State i fills up City.
Now my problem is till i have some records inside the Datasource it works fine, but as soon as i delete the last remaining record from the datasource, it throws error, it switches to the emptydatatemplate but it could not find the States Dropdownlist (based on which i am filling city dropdown). But once i refresh the page it works fine.
I don't understand which event to grab to place the codes
Here's what i am doing
Below function gets the stateid and fills the cities based on it
private void FillCitiesByStateId()
{
drpCity = grdLocationView.Controls[0].Controls[0].FindControl("drpCitiesAdd") as DropDownList;
drpState = grdLocationView.Controls[0].Controls[0].FindControl("drpStatesAdd") as DropDownList; // Fetches the States DropDown from EmptyDataTemplate.
if (drpState != null)
{
objCity.StateId = Convert.ToInt32(drpState.SelectedValue); //It always throws error on this line.
drpCity.DataSource = objCity.GetCitiesByStateId();
drpCity.DataTextField = "Name";
drpCity.DataValueField = "Id";
drpCity.DataBind();
}
}
Below is the code i which is used to bind the records in dropdowns
protected void grdLocationView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (dt.Rows.Count == 0)
{
FillCitiesByStateId();
}
else
{
if (e.Row.RowType == DataControlRowType.Header)
{
drpCity = e.Row.FindControl("drpCities") as DropDownList;
drpState = e.Row.FindControl("drpStates") as DropDownList;
objCity.StateId = Convert.ToInt32(drpState.SelectedValue);
drpCity.DataSource = objCity.GetCitiesByStateId();
drpCity.DataTextField = "Name";
drpCity.DataValueField = "Id";
drpCity.DataBind();
}
}
}
Can anyone provide any suggestion whats going wrong with it
Make sure you are only calling the FillCitiesByStateId() for appropriate row types. Maybe you're calling it for a footer row?
DataControlRowType Enumeration
instead of:
if (dt.Rows.Count == 0)
{
FillCitiesByStateId();
}
try:
if (e.Row.RowType == DataControlRowType.EmptyDataRow)
{
FillCitiesByStateId();
}
I have 3 dropdownlist which will have set of values from the database. In my page, I have different controls. I was planning to add this dropdownlist in a repeater control.
When a user selects a value, the value will be saved to the database, either by a save button inside the control or automatically.
Could you please let me know if this is possible? If yes, any code that can be shared would be helpful.
Yes, it's possible. The trick is that the DataSource for the dropdownlists are separate than the DataSource of the Repeater.
Here's the sample code:
protected void cmdSave_Click(object sender, EventArgs e)
{
foreach (RepeaterItem ri in GeneralRepeater.Items)
{
switch (ri.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
DropDownList GetValue = (DropDownList)ri.FindControl("GeneralDDL");
var sSelectedValue = GetValue.SelectedValue;
for (int index = 0; index <= PocDiagnoses.MAX_DIAGNOSIS; index++)
{
foreach (RepeaterItem ri1 in GeneralRepeater.Items)
{
int iItemIndex = ri1.ItemIndex;
DropDownList myDDL = (DropDownList)GeneralRepeater.Items[index].FindControl("GeneralDDL");
FirstPlanOfCare.Diagnoses.Diagnoses[index] = new PatientDiagnosis(myDDL.SelectedValue, new SynergyOnSetDate(new System.DateTime(Year, Month, Day)), "01/02/2011"); //Insert Diagnosis Value
}
}
break;
}
}
//Create
Chart.AddPlanOfCare(FirstPlanOfCare);
}