I've created a simple ASPX page that lists records in a GridView. The records are a list of incidents and one of the columns is the ID of the person who reported the incident.
The initial page shows all records but I would like to provide a filter for the ReportedBy column. I've gotten this working by allowing the user to type in the ReportedByID in a textbox and then clicking on the submit button. This refreshes the page as expected with the filtered view.
The code for this page is 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();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;
if (int.TryParse(txtReportedById.Text, out reportedById) == false)
{
reportedById = 0;
}
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}
To make it more user friendly, I decided to add a dropdown box populated with the ReportedBy names for the user to select which would then be used to filter on upon clicking the submit button. The dropdown box has names as the display items but the values should still be set to the IDs.
The problem I have is that the ID number I get from the dropdown box always comes up as the first element of the list rather than the one the user selected at the time they clicked on the submit button.
The code for this page with this implementation is as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
DataAccessObj daObj = new DataAccessObj();
foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}
if (IsPostBack == false)
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;
if (combobox.SelectedItem != null)
{
if (int.TryParse(combobox.SelectedItem.Value, out reportedById) == false)
{
reportedById = 0;
}
}
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}
Any help would be gratefully appreciated. TIA
Keep in mind that with WebForms the Page_Load code is executed before the event handler code for the control which created the postback.
You have to populate the list in the section where postbacks flags are checked, just like you do with the grid.
if (IsPostBack == false){
//bind the combobox
}
Otherwise, on a postback, the list will re-populate and the selection will be gone.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataAccessObj daObj = new DataAccessObj();
foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
Related
I have a drop down list with a button event that should send it's value for a textbox.But,even if I choose a value that is not the first one in the DDL,it only sends the value of the first item in the DDL. I was told to add the !IsPostBack in the page load,but it didn't help.
Codes:
protected void Page_Load(object sender, EventArgs e)
{
string testeddl;
codProfessor = Request.QueryString["id"];
if (db.conecta())
{
ddlTeste.Items.Clear();
ddlTesteAltDel.Items.Clear();
ddlQuestoes.Items.Clear();
listaX = db.retornaTestes(codProfessor);
for (int i = 0; i < listaX.Count; i++)
{
testeddl = listaX[i].nometeste;
ddlTesteAltDel.Items.Add(testeddl);
}
protected void btnBuscarTeste_Click(object sender, EventArgs e)
{
if (db.conecta())
{
int posic = ddlTesteAltDel.SelectedIndex;
txtNomeTeste.Text = listaX[posic].nometeste;
ddlaltdelTeste.Text = listaX[posic].materiateste;
}
}
}
}
In Page_Load, just need to indicate:
if(!IsPostBack()
{
// rest of the code.
}
I want to capture the selected date on my DropDown list, where there are five days will display on DropdownList.
I'm usually putting the default value on DropDown, but not this time because in the drop down list I want it always display the current date and the next five days. But I don't know how to capture the data.
<asp:DropDownList ID="ddldate" runat="server">
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
List<ListItem> items = new List<ListItem>();
for (int i = 0; i < 5; i++)
{
items.Add(new ListItem(
DateTime.Now.AddDays(i).ToShortDateString(),
DateTime.Now.AddDays(i).ToShortDateString()));
}
ddldate.DataSource = items;
ddldate.DataBind();
ddldate.Items[0].Selected = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
string deliverytime = ddldate.SelectedValue.ToString();
lbltest.Text = deliverytime;
}
You're repopulating the DropDownList for every postback and reloading the page, hence the SelectedValue property value may be different from the posted value. Just put a check against IsPostBack to prevent repopulating DropDownList data on postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ListItem> items = new List<ListItem>();
for (int i = 0; i < 5; i++)
{
items.Add(new ListItem(DateTime.Now.AddDays(i).ToShortDateString(), DateTime.Now.AddDays(i).ToShortDateString()));
}
ddldate.DataSource = items;
ddldate.DataBind();
ddldate.Items[0].Selected = true;
}
}
You should not bind data on PostBack, change your FormLoad code to below sample:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
List<ListItem> items = new List<ListItem>();
for (int i = 0; i < 5; i++)
{
items.Add(new ListItem(DateTime.Now.AddDays(i).ToShortDateString(), DateTime.Now.AddDays(i).ToShortDateString()));
}
ddldate.DataSource = items;
ddldate.DataBind();
ddldate.Items[0].Selected = true;
}
}
If you check the PostBack property as condition, your SelectedValue will keep, otherwise DropDown will bind on each page-post.
And I also recommend you to check SelectedValue status before use it, don't try to get value if this null, check the following code:
protected void Button1_Click(object sender, EventArgs e)
{
if(ddldate.SelectedValue != null)
{
string deliverytime = ddldate.SelectedValue.ToString();
lbltest.Text = deliverytime;
}
}
I have an existing drop down list(namely ddlA). On selecting a value in which, I am getting a cascading drop down list(ddlB). The requirement is, I need to create a button on the webform. By clicking the button, I would need to create drop down list dynamically of type ddlA. But here is the tricky part, I am required to present all the values in this dropdown except the selected value in the previous selection(s) of type ddlA.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<DropDownList> DDLList = new List<DropDownList>();
Session["DDLs"] = DDLList;
}
else
{
List<DropDownList> existingDropDowns = (List<DropDownList>)Session["DDLs"];
//Add all existing DropDownLists to Panel
foreach (DropDownList dropdown in existingDropDowns)
{
Panel1.Controls.Add(dropdown);
dropdown.AutoPostBack = true;
Panel1.Controls.Add(new LiteralControl("<br/>"));
}
Session["DDLs"] = existingDropDowns;
}
}
and here is my button click event code:
protected void ddlAdditionBtn_Click(object sender, EventArgs e)
{
List<DropDownList> existingDropDowns = (List<DropDownList>)Session["DDLs"];
DropDownList newDropDown = new DropDownList();
newDropDown.ID = "DDL" + existingDropDowns.Count.ToString();
existingDropDowns.Add(newDropDown);
Panel1.Controls.Add(newDropDown);
newDropDown.AutoPostBack = true;
Panel1.Controls.Add(new LiteralControl("<br/>"));
Session["DDLs"] = existingDropDowns;
}
Below is the code to connect the existing dropdown list with the database.
protected void GetDropDowndata()
{
DataTable ddlData= lookupCache.AccessLookupData(Constants.GroupSelectionFilter.ToString());
if (ddlData != null && ddlData.Rows.Count > 0)
{
ddlData.DefaultView.Sort = "DropDownValue";
ddlData = groupsData.DefaultView.ToTable();
ddlSelectGrp.DataSource = ddlData;
ddlSelectGrp.DataTextField = "DropDownValue";//ddlSelectGrp is the existing dropdown id
ddlSelectGrp.DataValueField = "DropDownBoxID";
ddlSelectGrp.DataMember = "DropDownGroup";
ddlSelectGrp.DataBind();
ddlSelectGrp.Items.Insert(1, Constants.GroupAll.ToString());
ddlSelectGrp.SelectedIndex = 1;
btnGroupSave.Enabled = true;
btnGroupSave.CssClass = "saveButton";
}
}
But I have no idea on how to connect the dynamically generated dropdownlist with the datasource and that too without the selected value(s) in the previous dropdown list(s).
This code doesn't work. I don't know what to fix.
public sealed partial class Home : Page
{
public Home()
{
this.InitializeComponent();
ComboBox1.Items.Add("Hindiiiii");
}
string selection = null;
private void ComboBox1_SelectedIndex(object sender, EventArgs e)
{
if (ComboBox1.SelectedIndex!=1)
{
selection = ComboBox1.SelectedItem.ToString();
}
}
private void Continue(object sender, RoutedEventArgs e)
{
if(selection != null)
{
if (selection == "Hindiiiii")
this.Frame.Navigate(typeof(MainPage));
else if (selection == "English")
this.Frame.Navigate(typeof(Home));
}
}
When a user selects Hindiiiii on the main screen and clicks continues he is not redirected to the next page (MainPage).
Let's say your main page looks like this:
You can store the selection in a variable:
string selection = null;
private void ComboBox1_SelectedIndex(object sender, EventArgs e)
{
if (ComboBox1.SelectedIndex!=-1)
{
selection = ComboBox1.SelectedItem.ToString();
}
}
Then in your click event you can pass parameters between your pages:
private void Continue(object sender, RoutedEventArgs e)
{
if(selection != null)
this.Frame.Navigate(typeof(SomePage), selection); //send the contents of the variable to another page
}
And let's say you had another page with a TextBox and a TextBlock:
In your other pages' OnNavigatedTo event, you can retrieve the parameters so you don't have to create a page for every selected language:
string selection = null;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
selection = e.Parameter.ToString();
languageTextBlock.Text = selection; //the textblox is now the selected language
//decide what the contents are based on the selection
if (selection == "English")
translation.Text = "Something in English";
else if (selection == "Hindi")
translation.Text = "Something in Hindi";
else if (selection == "German")
translation.Text = "Something in German";
//etc
}
When you go to the next page, this allows you to create your page based on the selected item. This image demonstrates this:
Alternatively, you can solve your problem by creating a page for every possible language:
private void Continue(object sender, RoutedEventArgs e)
{
if(selection != null)
{
if(selection == "English")
this.Frame.Navigate(typeof(EnglishPage));
else if(selection == "Hindi")
this.Frame.Navigate(typeof(HindiPage));
//and so on
}
}
I prefer to do it this way because it's a lot simpler.
Edit: I see Items in the property box but I'm not aware of how to use it to add combo box items. This is the way that I usually see it done:
Of course you'll need to replace MainPage with your page (if it's not already named MainPage).
Another edit:
If you added the items via the properties panel, you have to access the Content. Use this instead, if you want:
string selection = null;
private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ComboBox1.SelectedIndex != -1)
{
//selection = ComboBox1.SelectedItem.ToString();
selection = (ComboBox1.SelectedItem as ComboBoxItem).Content.ToString();
}
}
I have a gridview that has linkbuttons that call modalpopups and textboxes with values. I am trying to implement sorting for the gridview, but the if(!ispostback) statement I need for sorting prevents the modalpopup from appearing. It also does not sort the textboxes in the gridview. Is there a way to implement sorting without using ispostback in the page_load?
Here is the code for the modalpopup, gridview binding and sorting.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["sortOrder"] = "";
Bind_Gridview("", "");
loadModals();
}
}
protected void viewModal(object sender, EventArgs e)
{
...
mainPanel.Controls.Add(exstModal);
mainPanel.Controls.Add(exstModalBox);
exstModalBox.Show();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
Bind_Gridview(e.SortExpression, sortOrder);
}
public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}
return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}
protected void gv1_RowCommand(object sender, GridViewRowEventArgs e)
{
...
CheckBox cb = new CheckBox();
TextBox ca = new TextBox();
ca.Width = 20;
TextBox cga = new TextBox();
cga.Width = 20;
if (e.Row.RowType == DataControlRowType.DataRow) //Foreach row in gridview
{
while (dr1.Read())
{
ca.Text = dr1["cyla"].ToString();
cga.Text = dr1["cga"].ToString();
checkText = dr1["completed"].ToString();
if (checkText == "True")
{
cb.Checked = true;
}
else
{
cb.Checked = false;
}
}
...
dr1.Close();
conn1.Close();
e.Row.Cells[6].Controls.Add(ca);
e.Row.Cells[8].Controls.Add(cga);
e.Row.Cells[9].Controls.Add(cb);
...
}
A GridView has built-in sorting capabilities. Depending on the dataset you are using to populate the data, you likely don't need to manually handle anything manually, let alone with the ViewState.
Check out the second example on this MSDN page and note that it never does anything manually with the ViewState... the OnSorting and OnSorted events are there just to display extra information or to impose requirements:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
If you post a bit more of your code (including your .aspx pages, the markup for the modal popups, and the code for the loadModals() function, we might be able to better help you.