ASP.Net: GridView control and combobox woes - c#

I've got a GridView control and Combobox control that are both successfully populated in my Page_Load event (within a block that checks for IsPostBack == false).
I've got an empty button 'btnClick' event handler which will reload the page when clicked. Both the GridView and Combobox controls have their EnableViewState property set to True. The behaviour I was expecting and hoping for was:
Page will reload with the GridView control still populated.
Page will reload with Combobox still populated and the item selected by the user still set as the selected item.
Unfortunately, the behaviour I'm getting is as follows:
GridView control is now empty and shows no data.
Combobox is now empty.
Code as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
DataAccessObj daObj = new DataAccessObj();
foreach (DataRow dataRow in daObj.GetAllData())
{
ListItem listItem = new ListItem(dataRow.ToString(), dataRow.Id.ToString());
myCombobox.Items.Add(listItem);
}
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Do nothing
}
What I would like to do is allow the user to select an item from the Combobox. Upon clicking Submit, the GridView would be repopulated (based upon the selected item). The Combobox will remain populated and show the last selected item.
Can someone help explain where I might be going wrong? TIA

When you click your button, the page is posted back, in your page load, if it is a postback you need to databind the grid appropriately you need to add a condition to your page load event like
Firstly on your btn_click, you need to store the id selected with something like:
if (myCombobox.SelectedItem != null)
{
if (int.TryParse(myCombobox.SelectedItem.Value, out reportedById) == false)
{
reportedById = 0;
ViewState["reportedById"] = reportedById; // Need to remember which one was selected
}
}
Then On your Post Back
else (IsPostBack)
{
if (ViewState["reportedById"]) != null)
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(Convert.ToInt32(ViewState["reportedById"]));
IncidentGrid.DataBind();
myCombobox.SelectedItem.Value = ViewState["reportedById"].ToString(); // set combo
}
else
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}

Related

Listview databind causes lost of formview Data

within my code , after a research via a Formview , I need to call the listview.databind and this makes impossible to get the Formview data , even if in the screen they still appear .
this is my code
protected void DemandeSearchFormView_ItemInserting(object sender, FormViewInsertEventArgs e)
{
ListView listview = (ListView)panelPagination.FindControl("listdeclarations");
ViewState["search"] = "search";
listview.DataBind();
}
the databind() normally call this method
public DeclarationGeneraleBean RechercheByCritere()
{
DeclarationGeneraleBean declarationBean = new
DeclarationGeneraleBean();
declarationBean.IdService = (int) Session["idService"];
if (ViewState["search"] != null)
{
TextBox numOrdre =
(TextBox)DemandeSearchFormView.FindControl("numtxt");
}
the ViewState["search"] is null , I dont know why ?? it seems that the databind() recharge the page or something like this .
Have any one an idea how to deal with this ?
Do you set the viewstate in your page load event?
If yes, i think you should add a condition in your Page_Load event :
private void Page_Load()
{
if (!IsPostBack)
{
}
}
it prevent the data to be reloaded on this event, if a post is submited.

Dropdown list binding issue in asp.net

I have a placeholder which has some dropdownlist and a button, now this placeholder is initially hidden and when user makes any search on the page, based on that the placeholder gets visible and the dropdownlist gets filled, this is working absolutely fineNow the problem starts when i click on the button inside the placeholder (next to dropdownlist), at this point of time, all the dropdownlist gets blank. I understand first page load executes and because there are no bindings (as dropdowns are binded on search click) it would make it blank, but i am not getting once the dropdown has been binded why it would matter for the page load to unbind it. Here's my code:
Page Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
plcView.Visible = false;
}
}
Search Button Click:
protected void btnSearch_Click(object sender, EventArgs e)
{
try
{
if (!AppGlobal.IsSanadCompleted(AppGlobal.Sanads.Amma, txtITSId.Text))
{
lblErrorMessage.CssClass = "dnnFormMessage dnnFormWarning";
lblErrorMessage.Text = "You need Amma Sanad to attempt for Hifz Program.";
plcView.Visible = false;
}
else
{
plcView.Visible = true;
txtJuz.Text = (Hifz.GetLastJuzAttempted(txtITSId.Text) + 1).ToString();
drpAyahFrom.DataTextField = "Key";
drpAyahFrom.DataValueField = "Value";
drpAyahFrom.DataSource = objHifz.GetAyahListForHifzProgram(Convert.ToInt32(txtJuz.Text));
drpAyahFrom.DataBind();
drpAyahTo.DataTextField = "Key";
drpAyahTo.DataValueField = "Value";
drpAyahTo.DataSource = objHifz.GetAyahListForHifzProgram(Convert.ToInt32(txtJuz.Text));
drpAyahTo.DataBind();
drpGrade.DataSource = AppGlobal.GetGrades();
drpGrade.DataBind();
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
I even tried enabling EnableViewstate at page and also at skin (I am using Dotnetnuke) level, but still it does not makes any difference.
Can anyone please suggest where i would be getting wrong.
DotNetNuke is nothing but an ASP.Net app. So to look into your issue we have to delve into the Page Life-Cycle of an ASP.Net page. There you will notice a Page_Event called SaveStateComplete. You see, this is called just before the Render event(At this event the page is displayed to the end user). So any changes done after rendering the page will not be saved in to the ViewState by default. Since your DropDowns are blank during SaveStateComplete, after a PostBack you're getting empty DropDowns.
The solution is to forcefully save the DataSource in your custom ViewState. For ex. in your button click, add the following:
var obj = objHifz.GetAyahListForHifzProgram(Convert.ToInt32(txtJuz.Text)));
drpAyahFrom.DataSource = obj;
ViewState["myUniqueKey"] = obj;
Then at the Page_Load event, you can use:
if (!IsPostBack)
{
plcView.Visible = false;
}
else
{
if(ViewState["myUniqueKey"] != null)
{
drpAyahFrom.DataTextField = "Key";
drpAyahFrom.DataValueField = "Value";
drpAyahFrom.DataSource = ViewState["myUniqueKey"];
drpAyahFrom.DataBind();
}
}
You may have to perform the casting as per the requirement.

Overriding the Telerik RadGrid AddNewRecordButton functionality to redirect the user to a new page rather than add a new insert record row to the grid

Previously when my RadGrid was not a batch edit grid I was able to use the grid's AddNewRecord button to redirect the user to another page with the following code:
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == "InitInsert")
{
Response.Redirect(redirectUrl + "?ProductID=" + this.ProductId);
}
}
After I made my grid a batch edit grid the Add New Button doesn't go into the ItemCommand event anymore and instead tries adding an inline insert record row to the grid. Is there anyway I can still use this button and override its functionality to still redirect the user?
So I've tested this and confirmed what I suspected in the comments. When EditMode="Batch", the "Add New Record" button, along with others, no longer cause a postback. You can override this by removing the JavaScript of the OnClientClick in the RadGrid1_ItemCreated like so:
Add this to your RadGrid1 attributes:
OnItemCreated="RadGrid1_ItemCreated"
Code behind (note: there is actually a Button AND a LinkButton):
protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item.ItemType == Telerik.Web.UI.GridItemType.CommandItem) {
//This is the icon with the plus (+) sign unless you've changed the icon
Button iconButton = e.Item.FindControl("AddNewRecordButton");
if (iconButton != null) {
iconButton.OnClientClick = "";
}
//This is the words "Add New Record" or whatever you've called it
LinkButton wordButton = e.Item.FindControl("InitInsertButton");
if (wordButton != null) {
wordButton.OnClientClick = "";
}
}
}
This should allow the postback to happen and the code you posted should be able to run.

How to deselect a single Item in a listbox

I have a listbox on my asp page, and I was wondering if there was anyway in code behind or javascript to deselect a selected item in my listbox. the selection mode is single.
Any help please? I tried adding a handler on selectedindexchanged...but it doesn't hit it if I am clicking on the same selectedItem.
I fixed my issue as Andrew pointed out, by setting the SelectedIndex = -1;
But, this created weird behavior since now I would have A checkboxList being populated from the selected list item I chose, and there was no Idea to see which list item populated it after wards.
So What I did was added 2 more lines of code on top of what andrew suggested and it worked great.
var index = lstGroups.SelectedIndex;
lstGroups.SelectedIndex = -1;
lstGroups.Items[index].Attributes["style"] = "background-color:lightblue";
Thanks for pushing me in the right direction!
You can use the following workaround if your SelectionMode="Single" and you want to deselect an item on second click.
Create a property in your page to keep the last selected list item value using session. I am assuming the selected value in your listbox is always int
public int ListBoxLastSelected
{
get
{
if (Session["ListBoxLastSelected"] != null)
return Convert.ToInt32(Session["ListBoxLastSelected"]);
return -1;
}
set { Session["ListBoxLastSelected"] = value; }
}
Create the following method
private void EnableListboxDeselect()
{
if (!IsPostBack)
{
// Register a postback event whenever you click on the list item
ClientScriptManager cs = Page.ClientScript;
lstMyList.Attributes.Add("onclick", cs.GetPostBackEventReference(lstMyList, "clientClick"));
Session["ListBoxLastSelected"] = null;
}
if (IsPostBack)
{
// Ensure the postback is from js side
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "clientClick")
{
if (CorpListLastSelected == Convert.ToInt32(lstMyList.SelectedValue))
{
lstMyList.ClearSelection();
CorpListLastSelected = -1;
}
else
{
ListBoxLastSelected= Convert.ToInt32(lstMyList.SelectedValue);
}
}
}
}
On your Page_Load add the below code
protected void Page_Load(object sender, EventArgs e)
{
EnableListboxDeselect();
}

Updating textbox based on datagrid view

I have this datagrid view which links to the table answers in the database. The user can edit answers to questions in this form, but I'd like for the textbox to be updated as the button moves onto next answer. This is so the user can edit/delete stuff in the textbox and save it.
private void NextQuestion_Click(object sender, EventArgs e)
{
QuestionsBindingSource.MoveNext();
}
How can I get the textbox to refresh based on selected record in datagridview?
Since you are using a BindingSource, you can get the Current object, cast it to it's type, and get a value.
Let's assume you are bound to a DataTable:
private void NextQuestion_Click(object sender, EventArgs e)
{
if (QuestionsBindingSource != null)
{
QuestionsBindingSource.MoveNext();
if (QuestionsBindingSource.Current != null)
{
DataRow row = (DataRow)QuestionBindingSource.Current;
yourTextBox.Text = row["FieldYouWant"].ToString();
}
}
}
What you cast Current to and the subsequent value reference are both dependent upon what you are bound to (what QuestionsBindingSource is). Adjust this example accordingly.

Categories