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

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
}

Related

Why ViewState and Control Values lost on partial Postback using AJAXFileUpload?

I have a .aspx page containing button which opens the popup on button click.
The popup window have AJAXFileUpload control. When button is clicked to open the popup, session values are sent to popup and on page load these session values are assigned to ViewState and HiddenField, DataTable.
Problem:
When i click on Upload button in popup containing AjaxFileUploadit saves the images to the table in AJAXUploadComplete event. In this event i am not able to access the ViewState,HiddenField and DataTable Values dont know why?
Popup.aspx.cs
DataTable dt=new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
int noOfImages;
string[] imagePaths;
if (dt != null && dt.Rows.Count==0)
{
dt.Columns.Add("QuoteID");
dt.Columns.Add("PrepID");
dt.Columns.Add("IsPrep");
dt.Rows.Add(string.Empty, string.Empty, string.Empty);
}
if ((!IsPostBack ))
{
if (Session["IsPrep"] != null || ViewState["IsPrep"]!= null)
{
int Isprep = Convert.ToInt32(Session["IsPrep"].ToString());
if (Session["IsPrep"] != null)
{
ViewState["IsPrep"] = Session["IsPrep"];
ViewState["QuoteID"] = Convert.ToString(Session["QuoteIDForListing"]);
int intQuoteID = Convert.ToInt32(ViewState["QuoteID"]);
hdnQuoteID.Value = intQuoteID.ToString();
ViewState["PrepID"] = Convert.ToString(Session["PrepIDForListing"]);
if (dt != null && dt.Rows.Count > 0)
{
dt.Rows[0]["QuoteID"] = Convert.ToString(Session["QuoteIDForListing"]);
dt.Rows[0]["PrepID"] = Convert.ToString(Session["PrepIDForListing"]);
dt.Rows[0]["IsPrep"] = Convert.ToString(Session["IsPrep"]);
}
Session["IsPrep"] = null;
Session["QuoteIDForListing"] = null;
Session["PrepIDForListing"] = null;
}
}
}
}
protected void AjaxFileUpload1_UploadComplete1(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
//here: ViewState,HiddenField,DataTable values are all get cleared dont know why?
if (dt != null && dt.Rows.Count > 0)
{
//here dt is set to null any idea?
}
//if (!string.IsNullOrEmpty(Convert.ToString(ViewState["QuoteID"])))
if (!string.IsNullOrEmpty(Convert.ToString(hdnQuoteID.Value))&& hdnIsPrepId.Value=="0")
{
int QuoteID = Convert.ToInt32(ViewState["QuoteID"]);
///some code here
}
// else if (!string.IsNullOrEmpty(Convert.ToString(ViewState["PrepID"])))
else if (!string.IsNullOrEmpty(Convert.ToString(hdnPrepID.Value)) && hdnIsPrepId.Value == "1")
{
int PrepID = Convert.ToInt32(ViewState["PrepID"]);
///some code here
}
}
NOTE: Same functionality works fine on a page. But, used with the popup it flushed all the values of HiddenField,DataTable,ViewState.
Session cant be used to store data after popup opened because multiple instance of windows may be opened at a time.
Also, when query string is used with Popup to send values the AjaxFileUpload gives error as it appends its own querystring contextkey and guid.
Please suggest any solution/change?

Unable to load Controls from Empty Data Template in GridView asp.net

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();
}

ASP:Dropdownlist onselectedindexchanges function does not fire even when I set autopostback to true

I am using a wizard. and in step two the user can add information about a location that will be stored. He can add as many locations as he likes.
In step three I want to enter more information about the specific location.
To select which location to use I have ASP:dropdownlist that I populate when user enters stuff.
I want to change index but it just does not work It never goes into the function when I tried debugging. I am using a label to debug.
When I change the selected item the page reloads and the first item in the dropdown list is always selected even though I selected something else. I do not understand why that happens
here is what I have
ASPX File
Select location to enter data for:
<asp:DropDownList ID="s3_location_list" runat="server" AutoPostBack="true" OnSelectedIndexChanged="stepThree_location_list_SelectedIndexChanged">
</asp:DropDownList>
Current location index:
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
CS files
/*This is where I add data to the drop down list
protected void stepTwo_addLocationData(object Sender, System.EventArgs e)
{
//initialize a temporary string array to get all the data from the form
//Console.Write("AAAAA"+ Context.Items["IsRefreshed"]);
Boolean refreshed = (Boolean)Context.Items["IsRefreshed"];
if (!refreshed)
{
//if user is adding a new entry to the location table
LocationData new_location = new LocationData();
//add stuff to locationData
if (stepTwo_locationTableIndex == -1)
{
//add the new_location element into the location_data array
location_data.Add(new_location);
//redraw the table
DataRow dr = dt.NewRow();
dr["Location"] = new_location.City;
//dr["Name"] = loc;
dt.Rows.Add(dr);
}
else
{
location_data[stepTwo_locationTableIndex] = new_location;
dt.Rows[stepTwo_locationTableIndex]["Location"] = City.Text;
}
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
///CreateTable();
stepFive_setLocationListOptions();
stepThree_setLocationListOptions();
stepTwo_resetForm();
}
/*this is the page load on step 3
protected void stepThree_load()
{
if (!IsPostBack && Session["s_s3_locationDropdownIndex"] == null)
{
stepThree_locationDropdownIndex = s3_location_list.SelectedIndex;
Session["s_s3_locationDropdownIndex"] = stepThree_locationDropdownIndex;
}
else
{
stepThree_locationDropdownIndex = (int) Session["s_s3_locationDropdownIndex"];
}
s3_location_list.SelectedIndex = stepThree_locationDropdownIndex;
Label3.Text = "" + s3_location_list.SelectedIndex;
}
/*this is my where I populate the list
protected void stepThree_setLocationListOptions()
{
s3_location_list.Items.Clear();
int i = 0;
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
/* this is the function thats callled when selected index is changed.
protected void stepThree_location_list_SelectedIndexChanged(object sender, EventArgs e)
{
Label3.Text = "Hello";
}
I think the problem is the order of execution. You should only initialize a DropDownList once, otherwise it will overwrite your SelectedIndex. For example, use the OnInit event:
<asp:DropDownList ID="s3_location_list"
runat="server"
OnInit="s3_location_list_Init"/>
And write the event method like this:
protected void s3_location_list_Init(object sender, EventArgs e)
if (!IsPostBack) {
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
}

Gridview paging Show all Records

i have a gridview that has paging enabled. i also have a dropdown on the pager of the gridview where the user can select how many records per page they would like to retrieve. Once the dropdown is changed then an event is fired (shown below) to rerun the query with the updated results per page request. This works very well. I did however want to have a value "All" on the dropdown aswell and the method i used to impliment this is by disabling paging.
This all works brilliantly except for one issue. When the user selects "All" on the dropdown i would like to still show the pager once the gridview is updated. It doesnt show because i turned off paging but is there a way to show the pager again? See my code below for the event. (As you can see i renable the pager at the end but this has no effect)
thanks
damo
Code behind Event for Dropdown Change
void GridViewMainddl_SelectedIndexChanged(object sender, EventArgs e)
{
//changes page size
if ((((DropDownList)sender).SelectedValue).ToString() == "All")
{
GridViewMain.AllowPaging = false;
}
else
{
GridViewMain.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
}
//binds data source
Result fAuditOverallStatusLatest = new Result(sConn);
GridViewMain.DataSource = Result.getAuditOverallStatusLatest();
GridViewMain.PageIndex = 0;
GridViewMain.DataBind();
GridViewMain.AllowPaging = true;
GridViewMain.BottomPagerRow.Visible = true;
GridViewMain.TopPagerRow.Visible = true;
}
DDL Code behind
protected void GridViewMain_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList GridViewMainddl = new DropDownList();
//adds variants of pager size
GridViewMainddl.Items.Add("5");
GridViewMainddl.Items.Add("10");
GridViewMainddl.Items.Add("20");
GridViewMainddl.Items.Add("50");
GridViewMainddl.Items.Add("100");
GridViewMainddl.Items.Add("200");
GridViewMainddl.Items.Add("500");
GridViewMainddl.Items.Add("All");
GridViewMainddl.AutoPostBack = true;
//selects item due to the GridView current page size
ListItem li = GridViewMainddl.Items.FindByText(GridViewMain.PageSize.ToString());
if (li != null)
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.IndexOf(li);
GridViewMainddl.SelectedIndexChanged += new EventHandler(GridViewMainddl_SelectedIndexChanged);
//adds dropdownlist in the additional cell to the pager table
Table pagerTable = e.Row.Cells[0].Controls[0] as Table;
TableCell cell = new TableCell();
cell.Style["padding-left"] = "15px";
cell.Controls.Add(new LiteralControl("Page Size:"));
cell.Controls.Add(GridViewMainddl);
pagerTable.Rows[0].Cells.Add(cell);
//add current Page of total page count
TableCell cellPageNumber = new TableCell();
cellPageNumber.Style["padding-left"] = "15px";
cellPageNumber.Controls.Add(new LiteralControl("Page " + (GridViewMain.PageIndex + 1) + " of " + GridViewMain.PageCount));
pagerTable.Rows[0].Cells.Add(cellPageNumber);
}
}
Put this in your Page_Init:
GridViewMain.PreRender += new EventHandler(GridViewMain_PreRender);
Then elsewhere in your Page class:
void GridViewMain_PreRender(object sender, EventArgs e)
{
var pagerRow = (sender as GridView).BottomPagerRow;
if (pagerRow != null)
{
pagerRow.Visible = true;
}
}
Then for your drop down event:
void GridViewMainddl_SelectedIndexChanged(object sender, EventArgs e)
{
MyServices fServices = new FAServices(sConn);
Result fAuditOverallStatusLatest = new Result(sConn);
var data = Result.getAuditOverallStatusLatest();
//changes page size
if ((((DropDownList)sender).SelectedValue).ToString() == "All")
{
GridViewMain.PageSize = data.Count();
}
else
{
GridViewMain.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
}
//binds data source
GridViewMain.DataSource = data;
GridViewMain.PageIndex = 0;
GridViewMain.DataBind();
GridViewMain.AllowPaging = true;
}
In that PreRender event, you'll have to duplicate that code for the top pager.
Edit: To get All selected, make this change in GridViewMain_RowCreated:
if (li != null)
{
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.IndexOf(li);
}
else
{
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.Count - 1;
}

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