I am dynamically generating checkbox on the basis of text entered in a textbox. When any of the checkbox is checked\unchecked, the checkbox gets removed. When I inspect element I cannot find checkbox and its change event is not fired. All these controls are in update panel.
Code is as follows:
<ajax:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="txtProducts" runat="server" AutoPostBack="true" onblur="return validate();" OnTextChanged="txtProducts_TextChanged"></asp:TextBox>
</td></tr>
<tr>
<td>
<panel runat="server" id="panelDynamicCheckbox"></panel>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<ajax:AsyncPostBackTrigger ControlID="txtProducts" EventName="TextChanged" />
</Triggers>
</ajax:UpdatePanel>
Code Behind:
protected void txtProducts_TextChanged(object sender, EventArgs e)
{
string[] products = txtProducts.Text.Split(',');
CheckBox[] chk = new CheckBox[products.Length];
int countForCheckbox = 0;
foreach (string product in products)
{
chk[countForCheckbox] = new CheckBox();
chk[countForCheckbox].ID = product;
chk[countForCheckbox].Text = product;
chk[countForCheckbox].Checked = true;
chk[countForCheckbox].AutoPostBack = true;
chk[countForCheckbox].EnableViewState = true;
chk[countForCheckbox].CheckedChanged += new EventHandler(Dynamic_CheckChanged);
panelDynamicCheckbox.Controls.Add(chk[countForCheckbox]);
countForCheckbox++;
}
}
protected void Dynamic_CheckChanged(object sender, EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
lblProductDetails.Text = "Done";
}
On textchange it shows the checkboxes but when I uncheck checkbox is gets removed.
I got my answer.
On postback dynamically created elements get removed so on postback I have to generate elements again. So in page_load I did following:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
CheckBox[] chk = new CheckBox[products.Length];
int countForCheckbox = 0;
panelDynamicCheckbox.Controls.Clear();
foreach (string product in products)
{
chk[countForCheckbox] = new CheckBox();
chk[countForCheckbox].ID = product;
chk[countForCheckbox].Text = product;
chk[countForCheckbox].Checked = true;
chk[countForCheckbox].AutoPostBack = true;
chk[countForCheckbox].EnableViewState = true;
chk[countForCheckbox].CheckedChanged += new EventHandler(Dynamic_CheckChanged);
panelDynamicCheckbox.Controls.Add(chk[countForCheckbox]);
countForCheckbox++;
}
}
}
Related
I have read many articles on viewstate but I can't get my head around it.
Basically I want to have two listboxes with add and remove buttons and a Proceed button.
When the Proceed button is pressed, the previous is hidden and a textbox is presented for each item in the first list box with 2 drop down boxes to describe it + a textbox for each item in the second list box (also for the user to add a description).
I then want a Finalise Button to save all this information to a database.
So far I have the following code:
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
CreateDynamicControls();
Page.MaintainScrollPositionOnPostBack = true;
Build2.Visible = false;
Build3.Visible = false;
Build4.Visible = false;
Finish.Visible = false;
}
void AddC_Click(Object sender, EventArgs e)
{
criteria.Items.Add(addnewc.Text.ToString());
addnewc.Text = null;
}
void RemoveCriterion_Click(Object sender, EventArgs e)
{
for (int i = 0; i < criteria.Items.Count; i++)
{
if (criteria.Items[i].Selected)
{
criteria.Items.Remove(criteria.Items[i]);
i--;
}
}
}
void AddAlternative_Click(Object sender, EventArgs e)
{
alternatives.Items.Add(addnewa.Text.ToString());
addnewa.Text = null;
}
void RemoveAlternative_Click(Object sender, EventArgs e)
{
for (int i = 0; i < alternatives.Items.Count; i++)
{
if (alternatives.Items[i].Selected)
{
alternatives.Items.Remove(alternatives.Items[i]);
i--;
}
}
}
void Continue_Click(Object sender, EventArgs e)
{
Build1.Visible = false;
Build2.Visible = true;
Build3.Visible = true;
CreateDynamicControls();
Finish.Visible = true;
}
void CreateDynamicControls()
{
Build2.Controls.Clear();
Build3.Controls.Clear();
Build2.Controls.Add(new LiteralControl("<h3>Please define each criterion.</h3><p>By describing it and indicating if it is 1/2 and a/b.</p>"));
for (int i = 0; i < criteria.Items.Count; i++)
{
Build2.Controls.Add(new LiteralControl("<strong>" + criteria.Items[i].Text + "</strong> Description:<br />"));
TextBox criteriondesc = new TextBox();
Build2.Controls.Add(criteriondesc);
criteriondesc.ID = "c" + i.ToString();
criteriondesc.Rows = 3;
criteriondesc.Width = 850;
criteriondesc.TextMode = TextBoxMode.MultiLine;
Build2.Controls.Add(new LiteralControl("<br />"));
Build2.Controls.Add(new LiteralControl("Desc1: "));
DropDownList aim = new DropDownList();
aim.ID = i.ToString();
aim.Width = 250;
aim.Items.Add(new ListItem("1"));
aim.Items.Add(new ListItem("2"));
Build2.Controls.Add(aim);
Build2.Controls.Add(new LiteralControl(" Desc2: "));
DropDownList source = new DropDownList();
source.ID = i.ToString();
source.Width = 250;
source.Items.Add(new ListItem("a"));
source.Items.Add(new ListItem("b"));
Build2.Controls.Add(source);
Build2.Controls.Add(new LiteralControl("<br /><br />"));
}
Build3.Controls.Add(new LiteralControl("<h3>Please define each alternative.</h3><p>Please describe each alternaitve in detail.</p>"));
for (int i = 0; i < alternatives.Items.Count; i++)
{
Build3.Controls.Add(new LiteralControl("<strong>" + alternatives.Items[i].Text + "</strong> Description:<br />"));
TextBox altdesc = new TextBox();
altdesc.ID = "a" + i.ToString();
altdesc.Rows = 3;
altdesc.Width = 850;
altdesc.TextMode = TextBoxMode.MultiLine;
Build3.Controls.Add(altdesc);
Build3.Controls.Add(new LiteralControl("<br />"));
}
Build3.Controls.Add(new LiteralControl("<br /><h3>Review dates.</h3><p>Please select a date for a meeting.</p>"));
OboutInc.Calendar2.Calendar selectdates = new OboutInc.Calendar2.Calendar();
Build3.Controls.Add(selectdates);
}
void Finish_Click(Object sender, EventArgs e)
{
Build4.Visible = true;
foreach (var control in Build2.Controls)
{
if (control.GetType() == typeof(TextBox))
{
Build4.Controls.Add(new LiteralControl(((TextBox)control).Text + "<br>"));
}
}
foreach (var control in Build3.Controls)
{
if (control.GetType() == typeof(TextBox))
{
Build4.Controls.Add(new LiteralControl(((TextBox)control).Text + "<br>"));
}
}
}
</script>
<asp:Content runat="server" ID="MainContent" ContentPlaceHolderID="MainContent">
<asp:Panel ID="Build1" runat="server">
<h3>What is your aim?</h3>
<p>
<asp:TextBox ID="goal" runat="server" Width="850px"></asp:TextBox>
</p>
<h3>What are the criteria of your decision?</h3>
<p>
<asp:ListBox ID="criteria" runat="server" Rows="8" Width="850px"></asp:ListBox><br />
<asp:Button ID="RemoveCriterion" runat="server" Text="Remove" OnClick="RemoveCriterion_Click" />
<asp:TextBox ID="addnewc" runat="server" Width="650px"></asp:TextBox>
<asp:Button ID="AddC" runat="server" Text="Add" OnClick="AddC_Click" />
</p>
</p>
<h3>What are the alternatives of your decision?</h3>
<p>
<asp:ListBox ID="alternatives" runat="server" Rows="8" Width="850px"></asp:ListBox><br />
<asp:Button ID="RemoveAlternative" runat="server" Text="Remove" OnClick="RemoveAlternative_Click" />
<asp:TextBox ID="addnewa" runat="server" Width="650px"></asp:TextBox>
<asp:Button ID="AddAlternative" runat="server" Text="Add" OnClick="AddAlternative_Click" />
</p>
<p align="right"><asp:Button ID="continue" runat="server" Text="Continue" OnClick="Continue_Click" /></p>
</asp:Panel>
<asp:Panel ID="Build2" runat="server">
</asp:Panel>
<asp:Panel ID="Build3" runat="server">
</asp:Panel>
<asp:Panel ID="Build4" runat="server">
</asp:Panel>
<p align="right"><asp:Button ID="Finish" runat="server" Text="Finish" OnClick="Finish_Click" /></p>
</asp:Content>
As you can see, at the minute I am just trying to output the user's text from the dynamically created textbox fields.
However, I am getting the error
Failed to load viewstate. The control tree into which viewstate is
being loaded must match the control tree that was used to save
viewstate during the previous request. For example, when adding
controls dynamically, the controls added during a post-back must match
the type and position of the controls added during the initial
request.
at: Line 169: Build3.Controls.Add(altdesc);
Does anyone know how to fix this problem with the viewstate?
I am very new to ASP.NET, my background is mainly in WinForms.
Thank you for any help and advice!!
You are creating your controls too late. You should create them during the Init events of the page, and not Page Load. I suggest You read abit about page life cycle
I think the best way to do it, it would be :
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
CreateDynamicControls();
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
CreateDynamicControls();<br/>
}
Small sample:
http://class10e.com/Microsoft/which-method-should-you-add-to-the-web-page
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
I got a query regarding adding dynamic buttons with dynamic onclick events on a set of updatepanels.
I've simplified the scenario as the code I have so far is way too long and tied up..I've created a test page with 3 update panels.
In terms of the actual page the first updatepanel will be for the filters which will in turn update the second update panel. 2nd update panel will consist of all the results, depending on filters..this will be a table of buttons.
On the click of any of these buttons on the second update panel, depending on the ID of the button the results will be generated in the last update panel.
The problem I'm facing is tieing in the button click event when the buttons are created.
When I create the button from the onclick from the first update panel, it adds it to the placeholder but the click event does not fire at all.
Here is some code from my testing page.
test.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="False"
UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder id="ph2" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder id="ph3" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
Codebehind:
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Button up2button = new Button();
up2button.ID = "up2button";
ph2.Controls.Add(up2button);
up2button.Click += new EventHandler(up2button_Click); // Not being registered?
AsyncPostBackTrigger trigger1 = new AsyncPostBackTrigger();
trigger1.ControlID = "up2button";
trigger1.EventName = "Click";
UpdatePanel2.Triggers.Add(trigger1);
ScriptManager1.RegisterAsyncPostBackControl(up2button);
UpdatePanel2.Update();
}
protected void up2button_Click(object sender, EventArgs e) { //and not being fired
Button up3button = new Button();
up3button.ID = "up3button";
up3button.Click += new EventHandler(up3button_click);
ph3.Controls.Add(up3button);
AsyncPostBackTrigger trigger1 = new AsyncPostBackTrigger();
trigger1.ControlID = "up3button";
trigger1.EventName = "Click";
UpdatePanel3.Triggers.Add(trigger1);
UpdatePanel3.Update();
}
protected void up3button_click(object sender, EventArgs e) {
}
}
Thankyou for your time.
here's a quick sample, I find on the internet:
I've used a placeholder to hold the dynamically created controls - the button and textboxes on that button's click event.
and the code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ViewState["Add"] != null)
{
Button add = new Button();
add.Text = "Add";
add.Click += new EventHandler(add_Click);
PlaceHolder1.Controls.Add(add);
}
if (ViewState["textboxes"] != null)
{
int count = 0;
count = (int)ViewState["textboxes"];
for (int i = 0; i < count; i++)
{
textbox textbox_foradd = new TextBox();
textbox_foradd.ID = "textadd" + (i + 1).ToString();
PlaceHolder1.Controls.Add(textbox_foradd);
}
}
}
}
void add_Click(object sender, EventArgs e)
{
int count = 1;
if (ViewState["textboxes"] != null)
{
count += Convert.ToInt32(ViewState["textboxes"]);
}
TextBox textbox_foradd = new TextBox();
textbox_foradd.ID = "textadd" + count.ToString();
PlaceHolder1.Controls.Add(textbox_foradd);
ViewState["textboxes"] = count;
}
protected void Button1_Click(object sender, EventArgs e)
{
Button add = new Button();
add.Text = "Add";
PlaceHolder1.Controls.Add(add);
ViewState["Add"] = 1;
}
Also, you need to give unique ID to each control in case you add multiple of the same control.
Ex:
Add button with id 'ButtonA'
Add another button with id 'ButtonA'
will fail, after the postback your buttons will trigger the event properly, but the action will not do a proper refresh.
Making it looks like it is not refreshing anymore.
Instead generate a unique ID for each control you add dynamically (and save those IDs).
In the postback, recreate those controls and reassign the IDs properly.
Only then will the UI refresh properly.
I have an UpdatePanel, in it a GridView, and in it a Repeater. There is a button to add comment. This button post backs but id does not run the function code behind. Here is my code
<updatepanel>
<gridview>
<repeater>
<asp:Button ID="kitapVarYorumEkle" runat="server"
CommandArgument='<%#Eval("id") %>'
CommandName='<%# GridView1.Rows.Count.ToString() %>'
Text="Yorum ekle" class="blueButton"
OnClick="kitapVarYorumEkle_Click" />
</repeater>
</gridview>
</updatepanel>
Code inside the js is:
protected void kitapVarYorumEkle_Click(object sender, EventArgs e)
{
kitapVarYorum temp = new kitapVarYorum();
if (Session["id"] != null)
{
temp.uyeId = Convert.ToInt32(Session["id"]);
}
Button btn = (Button)sender;
temp.kitapVarId = Convert.ToInt32(btn.CommandArgument);
string text = "";
GridViewRow row = GridView1.Rows[Convert.ToInt32(btn.CommandName)];
if (row != null)
{
TextBox txt = row.FindControl("txtYorum") as TextBox;
if (txt != null)
{
text = txt.Text;
}
}
temp.icerik = text;
var db = Tools.DBBaglanti();
db.kitapVarYorums.InsertOnSubmit(temp);
db.SubmitChanges();
// Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
I have tried it outside the the controls and it works
Have you tried the ItemCommand approach?
<asp:Button
CommandArgument='<%#Eval("id") %>'
CommandName="yourCommandNameOfChoice"
Text="Yorum ekle"
ID="kitapVarYorumEkle"
class="blueButton" runat="server"
OnClick="kitapVarYorumEkle_Click" />
now add an ItemCommand event for your repeater:
protected void yourRepeater_ItemCommand(object source , RepeaterCommandEventArgs e)
{
switch(e.CommandName)
{
case "yourCommandNameOfChoice":
// Your Code Here
break;
}
}
Environment: ASP NET 2.0 - Production Server does not have Ajax Control Toolkit so no real Control toolkit to use here.
3 RadioButtons List:
List one loads, after postback, the item from list one is used to select a Lab value.
Once a lab value is selected a 3rd radiobuttonlist will populate. There are some textboxes but they are not shown in example. The textboxes postback themselves on changes. If both textboxes are
not empty, a record is created for the session.
Now if the 3rd radiobuttonlist is changed from the default a series of 3 hidden user controls appear which represent 3 levels of reasons for the change ( child/parent records in database ).
The problem I am having is when I select a different item on the radiobuttonlist the radiobutton 3 OnSelectedIndex is firing after my user controls fire. My user controls need the value of the 3rd list to go to the database and get the correct set of records associated with the lab.
The problem is because the last radiobuttonlist is not processed until after the web controls loads, the code to mount the user controls never happens.
Here is the basic HTML code:
<asp:RadioButtonList ID="rdoLab" runat="server" OnSelectedIndexChanged="rdoLab_OnSelectedIndexChange">
</asp:RadioButtonList>
<asp:TextBox ID="textbox1" runat="server" OnTextChanged="TextBoxProcess" />
<asp:TextBox ID="textbox2" runat="server" OnTextChanged="TextBoxProcess" />
<asp:RadioButtonList ID="rdoPrimary" RepeatColumns="3" OnSelectedIndexChanged="rdoPrimary_OnSelectedIndexChanged" runat="server" ToolTip="Select Normal, Hypo or Hyper - Normal is default value." AutoPostBack="True" >
<asp:ListItem Value="3" Text="Normal" Selected="true"/>
<asp:ListItem Value="1" Text="Hypo" />
<asp:ListItem Value="2" Text="Hyper" />
</asp:RadioButtonList>
<asp:Panel ID="UpdLab" runat="server" Visible="true" EnableViewState="true">
<asp:Table ID="tblAdmin" runat="server">
<asp:TableRow>
<asp:TableCell runat="server" id="tblCell1" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab1" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell2" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab2" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell3" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab3" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
Here is the page behind:
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad(e);
GetSessionVars();
if (CommonUI.strTest((string)Session["rdoLabs"]) && CommonUI.strTest((string)Session["rdoPrimary"]) && Convert.ToString(hrdoLabs.Value) == (string)Session["rdoLabs"])
{
divLabLvl.Visible = true;
// Get cboListItems from the web user controls...
Session["ArrLstItems"] = "";
ArrayList ArrLstItems = new ArrayList();
ArrayList GetWuc = GetWUCS();
for (int i = 0; i < GetWuc.Count; i++)
{
Lab wuc = (Lab)GetWuc[i];
CheckBoxList cboItemList = (CheckBoxList)wuc.FindControl("cboItems");
string cboItems = GetCboItemList(cboItemList);
HiddenField hcboItems = (HiddenField)wuc.FindControl("hcboItems");
}
Session["ArrLstItems"] = (ArrayList)ArrLstItems;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DbDataReader ddrGrp = rdoGroups();
if (ddrGrp.HasRows)
{
rdoGroup.DataSource = ddrGrp;
rdoGroup.DataBind();
}
ddrGrp.Close();
}
else
{
DbDataReader ddrLab = rdoUserLabs();
if (ddrLab.HasRows)
{
rdoLabs.DataSource = ddrLab;
rdoLabs.DataBind();
if (CommonUI.strTest((string)Session["rdoLabs"]))
{
if (Convert.ToInt32(Session["rdoLabs"]) > 0)
{
rdoLabs.SelectedValue = (string)Session["rdoLabs"];
SetLabCss();
}
}
}
ddrLab.Close();
}
}
protected void rdoGroup_OnSelectedIndexChanged(object sender, EventArgs e)
{
//...do some stuff
}
protected void rdoLabs_OnSelectedIndexChanged(object sender, EventArgs e)
{
//... reload
}
protected DbDataReader rdoGroups()
{
int group_type_id = GroupTypeId();
Group grp = new Group();
return grp.GetGroups(group_type_id);
}
protected DbDataReader rdoUserLabs()
{
RadioButtonList rdoGrp = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
int GroupId = Convert.ToInt32(rdoGrp.SelectedValue);
LabAbnormalReasons lar = new LabAbnormalReasons();
return lar.GetLabsList(GroupId);
}
protected void rdoPrimary_OnSelectedIndexChanged(object sender, EventArgs e)
{
Session["Save"] = ((RadioButtonList)sender).ID;
RadioButtonList rdoGroups = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
int UserId = Convert.ToInt32(Session["UserId"]);
int DocId = Convert.ToInt32(Session["DocId"]);
SubmitLab_Data(arrLstItems, arrOthers);
}
protected void GetSessionVars()
{
RadioButtonList rdoGroup = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoPrimary = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoPrimary");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
if (rdoGroup.SelectedIndex != -1)
{
Session["rdoGroup"] = (string)rdoGroup.SelectedValue;
}
if (rdoLabs.SelectedIndex != -1)
{
Session["rdoLabs"] = (string)rdoLabs.SelectedValue;
}
if (rdoPrimary.SelectedIndex != -1)
{
Session["rdoPrimary"] = (string)rdoPrimary.SelectedValue;
}
}
Here is example of user code:
THIS CODE NEVER FIRES BECAUSE the 3rd Button List data is not available here :
protected void Page_Load(object sender, EventArgs e)
{
/////*
//// * lab & Primary have been selected...
//// */
int lvl = SetLvlId();
int par_id = GetParentLvl();
Lab wuc = GetWuc(lvl);
if (wuc != null)
{
if (CommonUI.strTest(Convert.ToString(Session["rdoLabs"])) && CommonUI.strTest(Convert.ToString(Session["rdoPrimary"])))
{
// data in data base for this user, lab, doc identifier...
if (Convert.ToInt32(Session["rdoPrimary"]) > 0
{
// have user hdr data - see if item data is mapped...
// do some stuff here
}
}
}
}
I hope this is clear. I've att
---*--- Since original posting:
added simple javascript/OnDataBound
function Primary(object)
{
alert("Value Clicked :" + object);
}
protected void rdoPrimary_DataBound(object sender, EventArgs e)
{
RadioButtonList rdlPrimary = (RadioButtonList)sender;
foreach (ListItem li in rdlPrimary.Items)
{
li.Attributes.Add("onclick", "javascript:Primary('" + li.Value + "')");
}
}
Store and retrieve the values you want to retain in SaveViewState and LoadViewState methods and see if that works for you? Also look to the earlier and later lifecycle events for handling the logic - Init and OnPreRender. This has worked for me in the past.
I was creating another usercontrol with Telerik's RadGrid and Calendar.
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<table class="style1">
<tr>
<td>From</td>
<td>To</td>
</tr>
<tr>
<td><asp:Calendar ID="Calendar1" runat="server" SelectionMode="Day"></asp:Calendar></td>
<td><asp:Calendar ID="Calendar2" runat="server" SelectionMode="Day"></asp:Calendar></td>
</tr>
<tr>
<td><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /></td>
<td><asp:Button ID="btnClear" runat="server" Text="Clear" OnClick="btnClear_Click" /></td>
</tr>
</table>
<telerik:RadGrid ID="RadGrid1" runat="server">
<MasterTableView CommandItemDisplay="Top"></MasterTableView>
</telerik:RadGrid>
and I am using Linq in code-behind:
Entities1 entities = new Entities1();
public static object DataSource = null;
protected void Page_Load(object sender, EventArgs e) {
if (DataSource == null) {
DataSource = (from entity in entities.nsc_moneytransaction
select new {
date = entity.transaction_date.Value,
username = entity.username,
cashbalance = entity.cash_balance
}).OrderByDescending(a => a.date);
}
BindData();
}
public void BindData() {
RadGrid1.DataSource = DataSource;
}
protected void btnSubmit_Click(object sender, EventArgs e) {
DateTime startdate = new DateTime();
DateTime enddatedate = new DateTime();
if (Calendar1.SelectedDate != null && Calendar2.SelectedDate != null) {
startdate = Calendar1.SelectedDate;
enddatedate = Calendar2.SelectedDate;
var queryDateRange = from entity in entities.nsc_moneytransaction
where DateTime.Parse(entity.transaction_date.Value.ToShortDateString())
>= DateTime.Parse(startdate.ToShortDateString())
&& DateTime.Parse(entity.transaction_date.Value.ToShortDateString())
<= DateTime.Parse(enddatedate.ToShortDateString())
select new {
date = entity.transaction_date.Value,
username = entity.username,
cashbalance = entity.cash_balance
};
DataSource = queryDateRange.OrderByDescending(a => a.date);
} else if (Calendar1.SelectedDate != null) {
startdate = Calendar1.SelectedDate;
var querySetDate = from entity in entities.nsc_moneytransaction
where entity.transaction_date.Value == startdate
select new {
date = entity.transaction_date.Value,
username = entity.username,
cashbalance = entity.cash_balance
};
DataSource = querySetDate.OrderByDescending(a => a.date); ;
}
BindData();
}
protected void btnClear_Click(object sender, EventArgs e) {
Calendar1.SelectedDates.Clear();
Calendar2.SelectedDates.Clear();
}
The problems are, (1) when I click the submit button. the data in the RadGrid is not changed. (2) how can we check if there is nothing selected in the Calendar controls, because there is a date (01/01/0001) set even if we do not select anything from that calendar, thus Calendar1.SelectedDate != null is not enough. =(
Thanks.
When you bind a new datasource to the grid control you need to call Rebind to have the grid show the new data. Alternatively you could use NeedDataSource event (more elegant solution in my opinion)
For your second problem try this (assuming you're using ASP.NET Calendar and not Telerik DatePicker:
if(Calendar1.SelectedDate.Date == DateTime.MinValue) {
//no date selected
} else {
//date is selected
}