How to get next month of selected month? - c#

I have one drop down list of months like 'January' 'February'...'December' in asp.net c#
<asp:DropDownList ID="dlsalmonth" runat="server" class="form-control form-control-solid placeholder-no-fix">
<asp:ListItem>January</asp:ListItem>
<asp:ListItem>February</asp:ListItem>
<asp:ListItem>March</asp:ListItem>
<asp:ListItem>April</asp:ListItem>
<asp:ListItem>May</asp:ListItem>
<asp:ListItem>June</asp:ListItem>
<asp:ListItem>July</asp:ListItem>
<asp:ListItem>August</asp:ListItem>
<asp:ListItem>September</asp:ListItem>
<asp:ListItem>October</asp:ListItem>
<asp:ListItem>November</asp:ListItem>
<asp:ListItem>December</asp:ListItem>
</asp:DropDownList>
<div class="col-md-4" style="margin-top: 2%">
<asp:TextBox ID="txtnextmonth" runat="server" CssClass="form-control" placeholder="Next Month" ReadOnly="true"></asp:TextBox>
</div>
What I want is when I select a Month from this list I want exact next Month in my text box next to it. Let say if I select February from this drop down list then March should be displayed in my text box.

you can try something like this
protected void dlsalmonth_OnSelectedIndexChanged(object sender, EventArgs e)
{
txtnextmonth.Text = dlsalmonth.SelectedItem.Text == "December" ?
dlsalmonth.Items[0].Text :
dlsalmonth.Items[dlsalmonth.SelectedIndex + 1].Text;
}
and also dont forget to add AutoPostBack="True" or it will not go to dlsalmonth_OnSelectedIndexChanged event

You can use SelectedIndexChanged event and in that event use the selectedIndex property to find the next month. You will have to take care of December as the next item will be the first not at next index. You will need to set AutoPostBack property to true to postback on drop down selection change. You will also need to bind the SelectedIndexChanged event.
protected void dlsalmonth_SelectedIndexChanged(object sender, EventArgs e)
{
txtnextmonth.Text = dlsalmonth.Items[(dlsalmonth.SelectedIndex+1)%12].Text;
}
Its could be done on server side as show above but it is recommended to do it on client side to save postback. You can do this with javascript like this.
In HTML, bind the onchange javascript event and pass it dropdownlist object using this.
<asp:DropDownList ID="dlsalmonth" runat="server" onchange="dlsalmonthChange(this);" class="form-control form-control-solid placeholder-no-fix">
In Javascript, put the script tag just before the closing body tag. get the textbox object and assign next element of drop down taking care of December and January.
<script type="text/javascript" language="javascript">
function dlsalmonthChange(sel)
{
document.getElementById("<%= txtnextmonth.ClientID%>").value = sel.options[(sel.selectedIndex+1) % 12].text
}
dlsalmonthChange(document.getElementById("<%= dlsalmonth.ClientID%>")); // to set the textbox on form load
</script>
</body>
I explicitly called the dlsalmonthChange on page load to set the textbox for the first time when page loads.

You could use a client side solution. This will remove the need for an extra PostBack.
<script type="text/javascript">
$("#<%=dlsalmonth.ClientID %>").change(function () {
var index = $(this).prop('selectedIndex') + 1;
var nextValue = $("#<%=dlsalmonth.ClientID %> option").eq(index % 12).val();
$("#<%=txtnextmonth.ClientID %>").val(nextValue);
});
</script>

Related

Jquery calendar does not reload after GridView is populated

I have a simple page with Jquery datepicker, UpdateProgress, and GridView inside of UpdatePanel.
Here is a fragment from the page:
...
Select From Date: <input type="text" id="datepickerfrom" name="datepickerfrom"/>
Select To Date: <input type="text" id="datepickerto" name="datepickerto"/>
<asp:Button ID="btnGetData" runat="server" OnClick="BtnGetData_Click" Text="Get Error List" />
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/ajax-loader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
...MyGrid...
</ContentTemplate>
</asp:UpdatePanel>
...
This is the code behind method invoked when clicking on the button:
protected void BtnGetData_Click(object sender, EventArgs e)
{
string dateFrom = HttpUtility.HtmlEncode(Request.Form["datepickerfrom"]);
string dateTo = HttpUtility.HtmlEncode(Request.Form["datepickerto"]);
InputData data = new InputData(dateFrom, dateTo);
Session["inputData"] = data;
gvErrorLog.PageIndex = 0;
LoadLogErrorData(data);
}
When I first load the page and click on one of the Date's text boxes, jQuery datepicker is poped up. When I refresh the page, it pops up as well.
However, after clicking on the button and populating the GridView with the data, it is not displayed anymore.
What can be the reason?
Your tag is
<input type="text" id="datepickerfrom" name="datepickerfrom"/>
This is really the regular html tag. Microsoft ASP.NET does NOT keep the state (ie in ViewState) of regular html tag. After postback, the page life cycle effectively creates a new instance of Page (System.Web.UI.Page) object before sending response back to browser as html.
On the other hand, once you change to
<asp:TextBox ID="datepickerfrom" runat="server" />
You will see it in postback. Also the way you capture those 2 dates in code behind is obsolete (only seen in ASP 1.1).
The namespace for your text tag is
System.Web.UI.HtmlControls.HtmlInputText and the namespace for the server tag is System.Web.UI.WebControls.TextBox. They belong to different namespaces. Any controls in the HtmlControls are for legacy purpose.
You may change to asp:TextBox and access them from code behind as follows:
protected void BtnGetData_Click(object sender, EventArgs e)
{
string dateFrom = datepickerfrom.Text; // -- updated
string dateTo = datepickerto.Text; // -- updated
InputData data = new InputData(dateFrom, dateTo);
Session["inputData"] = data;
gvErrorLog.PageIndex = 0;
LoadLogErrorData(data);
}
If you insist on your tags, you can add a hidden variable and update those hidden variable on change event of your textboxes.
I assume your textboxes are set up like the following
$(function () {
$("#<%=datepickerfrom.ClientID%>").datepicker();
$("#<%=datepickerto.ClientID%>").datepicker();
});
I finally found the answer to my problem here:
http://www.jquerybyexample.net/2010/08/jquery-datepicker-does-not-work-after.html

Another SelectedIndexChanged PostBack Resetting Index

I really hate asking since there are so many similar issues related to SelectedIndexChanged not firing. However, I can't figure this one out. Here is my DDL:
<asp:DropDownList runat="server" ID="ddlPart1Country"
CssClass="form-control"
AutoPostBack="true"
OnSelectedIndexChanged="ddlPart1Country_SelectedIndexChanged" />
I have a master page setting EnableViewState="True", and it also has my ScriptManager and form element. Really, nothing out of the ordinary here. With it like this the SelectedIndexChanged will fire just fine. My problem comes in when wrapped by any other element, (e.g.: Panel, div, etc.) My DDL will fire a PostBack, but the index doesn't change, therefore not firing the SelectedIndexChanged event.
So, it will not change the index when for instance:
<div class="row">
<div class="form-group">
<label for="ddlPart1Country" class="col-sm-3 control-label">Country<i class="required"></i></label>
<div class="col-sm-4">
<asp:DropDownList runat="server" ID="ddlPart1Country" CssClass="form-control" AutoPostBack="true" OnSelectedIndexChanged="ddlPart1Country_SelectedIndexChanged" />
</div>
</div>
</div>
Identical DDL control, the only difference is its placement in the div.
And here is my codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
FillPart1Countries();
}
protected void FillPart1Countries()
{
var lstOptions = CacheValues.Countries;
if (lstOptions == null)
{
return;
}
ddlPart1Country.Items.Add(new ListItem(" -- Select Your Country -- ", ""));
foreach (var option in lstOptions.Result)
{
ddlPart1Country.Items.Add(new ListItem(option.Ctry, option.GENC0));
}
}
protected void ddlPart1Country_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlPart1Country.SelectedItem.Value == "")
return;
var lstOptions = FormPopulation.GetStatesAndProvences(ddlPart1Country.SelectedItem.Value);
ddlPart1StateOrProvence.Items.Clear();
ddlPart1StateOrProvence.Items.Add(new ListItem(" -- Select Your State/Provence -- ", ""));
foreach (var option in lstOptions.Result)
{
ddlPart1StateOrProvence.Items.Add(new ListItem(option.Name, option.GENC1));
}
lblCountrySelected.Text = ddlPart1Country.SelectedItem.Text;
upnlPart1State.Update();
}
I'm not rebuilding the DDL on PostBack. ViewState is enabled. I know it has to be something dumb I'm doing or not doing, but I can't see it. What am I missing?
After thinking about this, I think I may have fixed something like this a while ago by switching the <div> to <asp:Panel>. I'm not sure what the problem was, though, since it normally works fine.
Thanks to Steve's idea about CSS, I removed the script libraries I was using, too. One of them is for my client-side validation and there was a line there:
$.each($('div').children(), function() {
$(this).attr("name", $(this).attr("id"));
});
That forces the DOM to rename the name attribute to the ID of the ASP control. Removing that of course solved the issue. That's what I get for using a hack for client-side validation in the first place. Thanks to everyone that gave this a look.

dropdown initializing input type="text" on postback

I have several text boxes <input type="text"> as well a a dropdownlist<asp:DropDownList>
I prefer to use this asp control as I want to bind it with data. The thing is every time I make a selection the text boxes re-initializes due to post back.
<asp:DropDownList ID="drpPleaseSelect" runat="server" OnSelectedIndexChanged="drpPleaseSelect_SelectedIndexChanged" AutoPostBack="True" >
<asp:ListItem>[Please Select Yes Or No]</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
<input type="text" runat="server" id="txtLastName" onkeyup="checkTextBoxes()" onfocus="checkTextBoxes()" />
protected void drpPleaseSelect_SelectedIndexChanged(object sender, EventArgs e)
{
var valueDropdown = drpPleaseSelect.SelectedValue.ToString();
if (valueDropdown == "[Please Select Yes Or No]")
{
labChkDropDown.InnerHtml = "Please select yes Or no";
}
else if (valueDropdown == "Yes" || valueDropdown == "No")
{
//bind a different asp:dropdownlist with database data
}
}
Is there a way for my html text boxes not to be affected by postback as I make changes the index of the dropdown list?
You said that every time you make a selection that the text boxes re-initialize, are you setting them on PageLoad or a function that is called from PageLoad?
If that is the case I think you are missing a check for IsPostback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Do stuff that you only want done on the inital page load.
//Like setting up inital values in textboxes, etc.
}
}

radiobutton inside repeater always returns false

I have a repeater with radiobuttons in it.
<script type="text/javascript">
$(document).ready(function ()
{
$("#test input:radio").attr("name", "yourGroupName");
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="test">
<asp:Repeater runat="server" ID="rep" onitemdatabound="rep_ItemDataBound"
onitemcommand="rep_ItemCommand">
<ItemTemplate>
<asp:RadioButton ID="n" runat="server" Text='<%# Eval("name") %>' AccessKey='<%# Eval("id")%>' />
</ItemTemplate>
</asp:Repeater>
</div>
I am using the javascript at the top to fix the radiobutton bug in .net.
i bind a list to the repeater at page load, with a if (!Page.IsPostback) around it.
edit:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
rep.DataSource = z.Table.ToList();
rep.DataBind();
}
}
then i have a button, that when clicked should do something with the radio button that's been selected, this is the problem now:
foreach (RepeaterItem i in rep.Items)
{
RadioButton erb = i.FindControl("n") as RadioButton;
if (erb.Checked)
{
//do stuff
}
}
no matter which radiobutton i select, when i click the button and i debug the entire loop, every checkbox == false. i'm doing more stuff with the code but i've simplified it, because this is the biggest problem.
i have seen countless of topics about this issue and i have looked through them all but i still can't seem to get this to work.
Please try adding OnCheckedChanged="RadioButton1_OnCheckedChanged" AutoPostBack="true" on you radio button this will trigger post back on click of the button and you will be able to find the Checked one
I think this is all down to the sequence of events in ASP.NET .
Try putting your DataBind code in the Page_Init procedure, that way the state of the radiobuttons will be set by the time it reaches the Page_Load procedure.

Gridview event not firing

I have a requirement where i have to update a textbox if any of the value in my grid view changes.. I have a gridview with 2 rows ..
one a template field with label and another template field with a textbox...
my Grid view looks like
name value
a (empty textbox)
b (empty textbox)
c (empty textbox)
now when the user enters a value in teh text box it should automatically update another textbox which is linked to this.
Here my questions is when someone enters a value in the textbox an event should be fired!
(I am getting the names a,b,c, from database). i dont want to have an edit link or update link because all the values to be entered are mandatory!
i tried Grid_SelectedIndexChanged1 but this not firing.. is there something i am missing or i need to change so that the evant is fired and i can update the other textbox??
I am new to ASP.NET so please help!
Thanks in advance!
If the updates are supposed to be triggered when the text changes, you should use the OnTextChanged event of the TextBox, and set AutoPostBack to true.
EDIT
To avoid duplicating efforts here, using the above approach you can find the row index using the technique that Pankaj Garg outlined in his answer:
int rowIndex = ((GridViewRow)((TextBox)sender).NamingContainer).RowIndex;
The biggest caveat to this approach is that it's not forgiving of changes in the markup. If you were to wrap the TextBox in another control that implements INamingContainer, the example above would break. For example:
<asp:TemplateField>
<asp:Panel ID="Panel1" runat="server"> <!-- becomes the naming container -->
<asp:TextBox ID="TextBox1" runat="server" onchange='valueChanged(<%# Container.ItemIndex %>);' />
</asp:Panel>
</asp:TemplateField>
That being said, you would want to notate your markup accordingly so other developers know to be careful when making changes.
EDIT
As an alternative, you could also trigger the postback in JavaScript using the onchange event of the TextBox:
<script type="text/javascript">
valueChanged = function(rowIndex){
__doPostBack("<%= GridView1.ClientID %>", rowIndex);
}
</script>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" ...>
<Columns>
<asp:TemplateField>
<asp:TextBox ID="TextBox1" runat="server" onchange='valueChanged(<%# Container.ItemIndex %>);' />
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code-behind, override the RaisePostBackEvent method, and put your update logic there:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
base.RaisePostBackEvent(source, eventArgument);
if (source == GridView1)
{
int rowIndex = int.Parse(eventArgument);
TextBox txt = GridView1.Rows[rowIndex].FindControl("TextBox1") as TextBox;
if (txt != null)
{
var id = (int)GridView1.DataKeys[rowIndex]["ID"];
var text = txt.Text.Trim();
//update the database
}
}
}
You can check the Current Row Index like below...
((GridViewRow)((TextBox)sender).NamingContainer).RowIndex
Create a handler for OnTextChanged event and set the AutoPostBack Property True.
protected void TextBox_TextChanged(object sender, EventArgs e)
{
int CurrentGridIndex = ((GridViewRow)((TextBox)sender).NamingContainer).RowIndex
}

Categories