The issue I am having is I have two groups of radio buttons.
When I click "ALL" in either of them the SharePoint DatePicker Control has to be disabled with a showing custom date (as shown in the image). But as you see the first one got enabled when I clicked on the second group of radiobuttons.
Would appreciate if you help me with this issue.
Thanks.
Below are two groups of radio buttons:
//First Group
<asp:RadioButton ID="Rd4Month" Text="All" AutoPostBack="True" GroupName="GrpDuration" runat="server" OnCheckedChanged="rdgetDateforMonths" />
<asp:RadioButton ID="Rd1Month" Text="1 month" AutoPostBack="True" GroupName="GrpDuration" runat="server" OnCheckedChanged="rdgetDateforMonths" />
<asp:RadioButton ID="Rd2Month" Text="3 month" AutoPostBack="True" GroupName="GrpDuration" runat="server" OnCheckedChanged="rdgetDateforMonths" />
<asp:RadioButton ID="Rd3Month" Text="6 month" AutoPostBack="True" GroupName="GrpDuration" runat="server" OnCheckedChanged="rdgetDateforMonths" />
<asp:RadioButton ID="Rd5Month" Text="Other" AutoPostBack="True" GroupName="GrpDuration" runat="server" OnCheckedChanged="rdgetDateforMonths" />
//Second Group
<asp:RadioButton ID="Rd4BuildMonth" AutoPostBack="True" Text="All" GroupName="GrpBuildDuration" runat="server" OnCheckedChanged="rdgetBuildDateforMonths" />
<asp:RadioButton ID="Rd1BuildMonth" AutoPostBack="True" Text="1 month" GroupName="GrpBuildDuration" runat="server" OnCheckedChanged="rdgetBuildDateforMonths" />
<asp:RadioButton ID="Rd2BuildMonth" AutoPostBack="True" Text="3 month" GroupName="GrpBuildDuration" runat="server" OnCheckedChanged="rdgetBuildDateforMonths" />
<asp:RadioButton ID="Rd3BuildMonth" AutoPostBack="True" Text="6 month" GroupName="GrpBuildDuration" runat="server" OnCheckedChanged="rdgetBuildDateforMonths" />
<asp:RadioButton ID="Rd5BuildMonth" AutoPostBack="True" Text="Other" GroupName="GrpBuildDuration" runat="server" OnCheckedChanged="rdgetBuildDateforMonths" />
//SharePoint DateTimeControl
<table>
<tr>
<td style="vertical-align: middle;">
<asp:Label ID="Label4" runat="server" Text="Start:"></asp:Label>
</td>
<td style="vertical-align: middle;">
<SharePoint:DateTimeControl ID="dtcStartDate" runat="server" DateOnly="True" />
</td>
<td style="vertical-align: middle;">
<asp:Label ID="Label5" runat="server" Text="End:"></asp:Label>
</td>
<td style="vertical-align: middle;">
<SharePoint:DateTimeControl ID="dtcEndDate" runat="server" DateOnly="True" />
</td>
</tr>
</table>
And the codebehind:
protected void rdgetDateforMonths(object sender, EventArgs e)
{
//dtcStartDate.Enabled = true;
// dtcStartDate.ClearSelection();
// ViewState["rd4Month"] = "false";
if (Rd1Month.Checked)
{
dtcStartDate.ClearSelection();
dtcStartDate.Enabled = true;
dtcStartDate.SelectedDate = DateTime.Now.AddMonths(-1);
// Label1.Text = DateTime.Now.AddMonths(-1).ToString();
}
if (Rd2Month.Checked)
{
dtcStartDate.ClearSelection();
dtcStartDate.Enabled = true;
dtcStartDate.SelectedDate = DateTime.Now.AddMonths(-3);
}
if (Rd3Month.Checked)
{
dtcStartDate.ClearSelection();
dtcStartDate.Enabled = true;
dtcStartDate.SelectedDate = DateTime.Now.AddMonths(-6);
}
if (Rd4Month.Checked)
{
dtcStartDate.ClearSelection();
DateTime value = new DateTime(2012, 04, 01);
dtcStartDate.SelectedDate = value;
dtcStartDate.Enabled = false;
// ViewState["rd4Month"] = "true";
}
if (Rd5Month.Checked)
{
dtcStartDate.Enabled = true;
dtcStartDate.ClearSelection();
}
}
protected void rdgetBuildDateforMonths(object sender, EventArgs e)
{
// dtcBuildStartDate.ClearSelection();
// dtcBuildStartDate.Enabled = true;
// ViewState["rd4BuildMonth"] = "false";
if (Rd1BuildMonth.Checked)
{
dtcBuildStartDate.Enabled = true;
dtcBuildStartDate.ClearSelection();
dtcBuildStartDate.SelectedDate = DateTime.Now.AddMonths(-1);
}
if (Rd2BuildMonth.Checked)
{
dtcBuildStartDate.ClearSelection();
dtcBuildStartDate.Enabled = true;
dtcBuildStartDate.SelectedDate = DateTime.Now.AddMonths(-3);
}
if (Rd3BuildMonth.Checked)
{
dtcBuildStartDate.Enabled = true;
dtcBuildStartDate.ClearSelection();
dtcBuildStartDate.SelectedDate = DateTime.Now.AddMonths(-6);
}
if (Rd4BuildMonth.Checked)
{
dtcBuildStartDate.Enabled = false;
dtcBuildStartDate.ClearSelection();
DateTime value = new DateTime(2012, 04, 01);
dtcBuildStartDate.SelectedDate = value;
dtcBuildStartDate.Enabled = false;
// ViewState["rd4BuildMonth"] = "true";
}
if (Rd5BuildMonth.Checked)
{
dtcBuildStartDate.Enabled = true;
dtcBuildStartDate.ClearSelection();
}
}
protected void Page_Load(object sender, EventArgs e)
{
//dtcStartDate.MaxDate = System.DateTime.Today;
dtcBuildStartDate.MaxDate = DateTime.Now.AddMonths(-1);
dtcStartDate.MaxDate = DateTime.Now.AddMonths(-1);
dtcEndDate.MaxDate = System.DateTime.Today;
dtcBuildEndDate.MaxDate = System.DateTime.Today; ;
lblErrorMsg.Text = "";
// When the page loads 1st time
if (!Page.IsPostBack)
{
try
{
Rd1Month.Checked = true;
Rd1BuildMonth.Checked = true;
dtcEndDate.SelectedDate = System.DateTime.Today; // set end date calendar to today's date
dtcBuildEndDate.SelectedDate = System.DateTime.Today;
dtcStartDate.SelectedDate = DateTime.Now.AddMonths(-1);
dtcBuildStartDate.SelectedDate = DateTime.Now.AddMonths(-1);
}
catch (Exception ex)
{
lblErrorMsg.Text += ex.Message;
}
}
}
After I modified the Enable for DateTimeControl to False
<SharePoint:DateTimeControl ID="dtcBuildStartDate" runat="server" DateOnly="True" Enabled="False" />
After reviewing the Page_Load method that you just added and reading the comment to my previous post. It looks like the problem is with the way the share point date time control acts. You can try adding EnableViewState="true".
<SharePoint:DateTimeControl ID="dtcBuildStartDate" runat="server" DateOnly="True" Enabled="False" EnableViewState="true" />
If viewstate is not turned on then every time your page posts back it reloads the default value from the aspx page definition. This would also affect things like the control's value not being maintained after a postback etc. If the enableviewstate doesn't work then you could try adding storing the state yourself in ViewState then on each postback you would have to manage this value, but it might get complicated with dealing with changes etc.
You can also try the following on page load:
protected void Page_Load(object sender, EventArgs e)
{
//dtcStartDate.MaxDate = System.DateTime.Today;
dtcBuildStartDate.MaxDate = DateTime.Now.AddMonths(-1);
dtcStartDate.MaxDate = DateTime.Now.AddMonths(-1);
dtcEndDate.MaxDate = System.DateTime.Today;
dtcBuildEndDate.MaxDate = System.DateTime.Today; ;
lblErrorMsg.Text = "";
// When the page loads 1st time
if (!Page.IsPostBack)
{
try
{
Rd1Month.Checked = true;
Rd1BuildMonth.Checked = true;
dtcEndDate.SelectedDate = System.DateTime.Today; // set end date calendar to today's date
dtcBuildEndDate.SelectedDate = System.DateTime.Today;
dtcStartDate.SelectedDate = DateTime.Now.AddMonths(-1);
dtcBuildStartDate.SelectedDate = DateTime.Now.AddMonths(-1);
}
catch (Exception ex)
{
lblErrorMsg.Text += ex.Message;
}
}
SetDateBoxEnabled();
}
private void SetDateboxEnabled()
{
if (Rd4BuildMonth.Checked)
{
dtcBuildStartDate.Enabled = false;
}
else
{
dtcBuildStartDate.Enabled = true;
}
if (Rd4Month.Checked)
{
dtcStartDate.Enabled = false;
}
else
{
dtcStartDate.Enabled = true;
}
}
Related
I am creating a quiz application in ASP.net (c#) and I currently have one question at a time displaying with the use of a datapager. However, when i move from question 1 to question 2 and then back to question 1 the radiobutton selection disappears.
EDIT - I now have the radio button retaining a selection whenever I move from next to previous, HOWEVER, If I chose radiobutton1 and then move on to question 2, It has radiobutton1 already selected, even though I am yet to answer that question. So for some reason whatever selection I make on question 1 is being duplicated to the other questions.
Question1 example
Question2 example
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="lvCustomers" runat="server" GroupPlaceholderID="groupPlaceHolder1"
ItemPlaceholderID="itemPlaceHolder1" OnPagePropertiesChanging="OnPagePropertiesChanging" OnPreRender="ListPager_PreRender">
<LayoutTemplate>
<div id="itemPlaceHolder1" runat="server">
</div>
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvCustomers" PageSize="1">
<Fields>
<asp:NextPreviousPagerField runat="server" ButtonType="Link"
ShowFirstPageButton="false"
ShowPreviousPageButton="true"
ShowNextPageButton="false" />
<asp:NumericPagerField ButtonType="Link" />
<asp:NextPreviousPagerField ButtonType="Link"
ShowNextPageButton="true"
ShowLastPageButton="false"
ShowPreviousPageButton="false" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("QuestionID")%>'></asp:Label><br />
<asp:Label ID="Label1" runat="server" Text='<%#Eval("QuestionText")%>'></asp:Label><br />
<li>
<asp:RadioButton ID="Radio1" Text='<%#Eval("Answer1") %>' GroupName="radiobtns" EnableViewState="true" runat="server" />
</li>
<li>
<asp:RadioButton ID="Radio2" runat="server" GroupName="radiobtns" EnableViewState="true" Text='<%#Eval("Answer2") %>' />
</li>
<li>
<asp:RadioButton ID="Radio3" runat="server" GroupName="radiobtns" EnableViewState="true" Text='<%#Eval("Answer3") %>' />
</li>
<li>
<asp:RadioButton ID="Radio4" runat="server" GroupName="radiobtns" EnableViewState="true" Text='<%#Eval("Answer4") %>' />
</li>
<br />
</ItemTemplate>
</asp:ListView>
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</p>
</form>
</body>
</html>
namespace WebApplication2.WebForms
{
public partial class _1QuestionQuiz : System.Web.UI.Page
{
string userAns;
int QuestionID;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindListView();
if (Session["QuizID"] != null)
{
int QuizID = Convert.ToInt32(Session["QuizID"]);
}
}
}
protected void ListPager_PreRender(object sender, EventArgs e)
{
if (Session["DTSource"] != null)
{
lvCustomers.DataSource = Session["DTSource"];
lvCustomers.DataBind();
}
GetSelections();
}
private void BindListView()
{
SqlConnection conn = new SqlConnection();
string connString = ConfigurationManager.ConnectionStrings["test1ConnectionString"].ConnectionString;
SqlCommand Cmd = new SqlCommand();
conn.ConnectionString = connString;
conn.Open();
if (lvCustomers != null)
{
foreach (ListViewItem item in lvCustomers.Items)
{
Label lbl = (Label)item.FindControl("Label2");
if (lbl != null)
{
QuestionID = Convert.ToInt32(lbl.Text);
ViewState["qstion"] = QuestionID;
}
RadioButton rd1 = (RadioButton)item.FindControl("Radio1");
RadioButton rd2 = (RadioButton)item.FindControl("Radio2");
RadioButton rd3 = (RadioButton)item.FindControl("Radio3");
RadioButton rd4 = (RadioButton)item.FindControl("Radio4");
if (rd1.Checked)
{
userAns = rd1.Text;
ViewState["Radio1"] = rd1.Text;
}
else if (rd2.Checked)
{
userAns = rd2.Text;
ViewState["Radio2"] = rd2.Text;
}
else if (rd3.Checked)
{
userAns = rd3.Text;
ViewState["Radio3"] = rd3.Text;
}
else if (rd4.Checked)
{
userAns = rd4.Text;
ViewState["Radio4"] = rd4.Text;
}
SqlCommand comm = new SqlCommand("InsertSelections", conn);
comm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(comm);
SqlParameter p1 = new SqlParameter("Answer", userAns);
SqlParameter p2 = new SqlParameter("QuestionID", QuestionID);
SqlParameter p3 = new SqlParameter("QuizID", (Session["QuizID"]));
comm.Parameters.Add(p1);
comm.Parameters.Add(p2);
comm.Parameters.Add(p3);
comm.ExecuteNonQuery();
}
}
}
private void GetSelections()
{
foreach (ListViewItem item in lvCustomers.Items)
{
Label lbl = (Label)item.FindControl("Label2");
if (lbl != null)
{
QuestionID = Convert.ToInt32(lbl.Text);
}
RadioButton rd1 = (RadioButton)item.FindControl("Radio1");
RadioButton rd2 = (RadioButton)item.FindControl("Radio2");
RadioButton rd3 = (RadioButton)item.FindControl("Radio3");
RadioButton rd4 = (RadioButton)item.FindControl("Radio4");
//Try radiobutton 1 as a tester
if (rd1 != null)
{
if (lbl != null && ViewState["Radio1"] != null)
{
rd1.Checked = true;
}
}
if (rd2 != null)
{
if (lbl != null && ViewState["Radio2"] != null)
{
rd2.Checked = true;
}
}
if (rd3 != null)
{
if (lbl != null && ViewState["Radio3"] != null)
{
rd3.Checked = true;
}
}
if (rd4 != null)
{
if (lbl != null && ViewState["Radio4"] != null)
{
rd4.Checked = true;
break;
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Score.aspx", false);
}
protected void OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
(lvCustomers.FindControl("DataPager1") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
BindListView();
}
}
}
Try overriding LoadViewState and SaveViewState to maintain the state of your radio buttons. For example, try something like the following, and pull the values back out of ViewState wherever you need them:
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (ViewState["Radio1"] != null)
Radio1.Text = (int)ViewState["Radio1"];
...
}
protected override object SaveViewState()
{
ViewState["Radio1"] = Radio1.Text;
...
return base.SaveViewState();
}
I have a problem. I created a couple of custom DataControlFields because I need to display data that doesn't come from a DataSource on a DataGrid.
I managed to get the controls unto the GridView but I can't manage to solve a couple of issues.
My controls do not persist their values between postbacks. I have the markup sitting inside an UpdatePanel which I set to Conditional. I then configured my triggers, excluding those of the GridView. I also tried setting the UpdateMode to Always. I get the same behavior here.
Here is my markup:
<asp:UpdatePanel UpdateMode="Conditional" ID="reportchooserUpdatePanel" runat="server">
<ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ddlMonth" EventName="Load" />
<asp:PostBackTrigger ControlID="ddlMonth" EventName="SelectedIndexChanged" />
<asp:PostBackTrigger ControlID="ddlYear" EventName="DataBinding" />
<asp:PostBackTrigger ControlID="ddlYear" EventName="SelectedIndexChanged
<asp:PostBackTrigger ControlID="GenerateReportsButton" EventName="Click" />
</Triggers>
<table class="ms-formtable">
<tr>
<td class="ms-formlabel">
<asp:Label ID="MonthYearLabel" runat="server" Text=""></asp:Label>
</td>
<td class="ms-formbody align-right">
<asp:DropDownList OnSelectedIndexChanged="ddlMonth_SelectedIndexChanged" AutoPostBack="true" runat="server" ID="ddlMonth" OnLoad="ddlMonth_Load">
<asp:ListItem Value="1">Januar</asp:ListItem>
<asp:ListItem Value="2">Februar</asp:ListItem>
<asp:ListItem Value="3">März</asp:ListItem>
<asp:ListItem Value="4">April</asp:ListItem>
<asp:ListItem Value="5">Mai</asp:ListItem>
<asp:ListItem Value="6">Juni</asp:ListItem>
<asp:ListItem Value="7">Juli</asp:ListItem>
<asp:ListItem Value="8">August</asp:ListItem>
<asp:ListItem Value="9">September</asp:ListItem>
<asp:ListItem Value="10">Oktober</asp:ListItem>
<asp:ListItem Value="11">November</asp:ListItem>
<asp:ListItem Value="12">Dezember</asp:ListItem>
</asp:DropDownList>
</td>
<td class="ms-formbody align-right">
<asp:DropDownList OnSelectedIndexChanged="ddlYear_SelectedIndexChanged" AutoPostBack="true" OnDataBinding="ddlYear_DataBinding" ID="ddlYear" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td style="width:100%;" class="ms-formbody" colspan="3">
<asp:GridView AutoGenerateColumns="false" ShowHeaderWhenEmpty="true" CssClass="grid-view" Width="100%" ID="gvProjects" runat="server">
</asp:GridView>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td class="ms-formtoolbar align-right" colspan="3">
<asp:HyperLink Target="_blank" Font-Size="X-Small" ID="hlGembox" NavigateUrl="http://www.gemboxsoftware.com/spreadsheet/free-version" runat="server"></asp:HyperLink>
<asp:Button OnClientClick="AddNotification('Please wait...')" ID="GenerateReportsButton" runat="server" Text="" OnClick="GenerateReportsButton_Click" />
</td>
<td></td>
<td></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
And here is the code of one of my custom DataControlFields. They are basically the same except for the controls they display:
class TemplateDropDownControl : DataControlField
{
SPList reportslist = ListItemHelper.GetReportsList();
protected void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
string ID = Guid.NewGuid().ToString();
DropDownList list = new DropDownList();
list.ID = ID;
FillContentTypeDropDown(list);
cell.Controls.Add(list);
}
public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
{
//Call the base method.
base.InitializeCell(cell, cellType, rowState, rowIndex);
this.InitializeDataCell(cell, rowState);
}
protected override DataControlField CreateField()
{
return new BoundField();
}
public string DataField
{
get
{
object value = base.ViewState["DataField"];
if (value != null)
{
return value.ToString();
}
else
{
return string.Empty;
}
}
set
{
base.ViewState["DataField"] = value;
this.OnFieldChanged();
}
}
public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
{
DropDownList list = cell.Controls[0] as DropDownList;
ListItem selectedValue = list.SelectedItem;
if (dictionary.Contains(DataField))
dictionary[DataField] = selectedValue.Value;
else
dictionary.Add(DataField, selectedValue.Value);
}
private void FillContentTypeDropDown(DropDownList ddlContentTypes)
{
if (reportslist == null)
return;
SPContentTypeCollection cts = reportslist.ContentTypes;
ddlContentTypes.Items.Clear();
foreach (SPContentType ct in cts)
{
ddlContentTypes.Items.Add(new ListItem() { Text = ct.Name, Value = ct.DocumentTemplateUrl + ct.DocumentTemplate.Replace("~site", "") });
}
}
}
And lastly, here is the code where I add these to my page. I set the AutoGenerateColumns property of the GridView to false in markup:
private void BindDataGrid()
{
DataTable table = new DataTable();
table = new DataTable();
table.Columns.Add(ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString));
table.Columns.Add(ResourceHelper.LoadResource(ResourceName.TemplateString));
table.Columns.Add(ResourceHelper.LoadResource(ResourceName.FileFormatString));
gvProjects.Columns.Clear();
gvProjects.DataSource = null;
//Fill DataTable here...
BoundField projectnumberField = new BoundField();
projectnumberField.HeaderText = ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString);
projectnumberField.DataField = ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString);
FileFormatCheckboxControl checkBoxControl = new FileFormatCheckboxControl();
checkBoxControl.DataField = ResourceHelper.LoadResource(ResourceName.FileFormatString);
checkBoxControl.HeaderText = ResourceHelper.LoadResource(ResourceName.FileFormatString);
TemplateDropDownControl dropDownControl = new TemplateDropDownControl();
dropDownControl.DataField = ResourceHelper.LoadResource(ResourceName.TemplateString);
dropDownControl.HeaderText = ResourceHelper.LoadResource(ResourceName.TemplateString);
gvProjects.Columns.Add(projectnumberField);
gvProjects.Columns.Add(dropDownControl);
gvProjects.Columns.Add(checkBoxControl);
gvProjects.DataSource = table;
gvProjects.DataBind();
}
Anybody know what I'm doing wrong here?
EDIT: Maybe I should be mentioning that I display the form in a Sharepoint modal dialog.
Ok I solved it another way since I had not idea why my problem kept happening. I just use a asp:Table now and generate the whole thing from code-behind. I have one method for this which I call on every page postback. It's important to note to call this method only from Page_Load. It didn't work when I called it from Page_Init.
Here is my code:
private void BindDataGrid()
{
GenerateReportsButton.Enabled = true;
reportsTable.Rows.Clear();
TableHeaderRow headerrow = new TableHeaderRow();
TableHeaderCell pnumberheader = new TableHeaderCell();
TableHeaderCell templateheader = new TableHeaderCell();
TableHeaderCell fileFormatHeader = new TableHeaderCell();
pnumberheader.Text = ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString);
templateheader.Text = ResourceHelper.LoadResource(ResourceName.TemplateString);
fileFormatHeader.Text = ResourceHelper.LoadResource(ResourceName.FileFormatString);
headerrow.Cells.Add(pnumberheader);
headerrow.Cells.Add(templateheader);
headerrow.Cells.Add(fileFormatHeader);
reportsTable.Rows.Add(headerrow);
if (ddlYear.SelectedItem == null || ddlMonth.SelectedItem == null)
{
int index = reportsTable.Rows.Add(new TableRow());
TableCell cell = new TableCell();
cell.ColumnSpan = 3;
cell.Text = ResourceHelper.LoadResource(ResourceName.NoListItemsForMonthYear);
reportsTable.Rows[index].Cells.Add(cell);
GenerateReportsButton.Enabled = false;
return;
}
//Get items here
if (items.Count == 0)
{
int index = reportsTable.Rows.Add(new TableRow());
TableCell cell = new TableCell();
cell.ColumnSpan = 3;
cell.Text = ResourceHelper.LoadResource(ResourceName.NoListItemsForMonthYear);
reportsTable.Rows[index].Cells.Add(cell);
GenerateReportsButton.Enabled = false;
return;
}
else
InsertRowIntoProjectTable("Intern", "Intern");
List<string> processedReports = new List<string>();
foreach(SPListItem item in items)
{
if (item[Variables.projectNumberField].ToString() != "Intern" && !processedReports.Contains(item[Variables.activityProject].ToString()))
{
InsertRowIntoProjectTable(item[Variables.activityProject].ToString(), item.ID.ToString());
processedReports.Add(item[Variables.activityProject].ToString());
}
}
}
Then you can just read the data like this:
foreach(TableRow row in reportsTable.Rows)
{
//Important since foreach also iterates over headerrow
if (row.Cells[1].Controls.Count > 0 && row.Cells[1].Controls[0] is DropDownList)
{
string value1= row.Cells[0].Text;
string value2= ((DropDownList)row.Cells[1].Controls[0]).SelectedValue;
//do stuff with the data
}
}
If anybody still finds the answer to my specific problem above, feel free to add it. I will mark it as accepted once verified that it works.
I have the following code-behind:
Random rndNum;
int inFirstOne, inSecondOne;
protected void Page_Load(object sender, EventArgs e)
{
rndNum = new Random();
int inFirst = rndNum.Next(1, 51);
int inSecond = rndNum.Next(50, 101);
lblFirst.Text = inFirst.ToString();
inFirstOne = inFirst;
lblSecond.Text = inSecond.ToString();
inSecondOne = inSecond;
}
public void ValidateForm(object sender, EventArgs e)
{
string strNum = tbValidation.Text;
int inCalc = inFirstOne + inSecondOne;
if (inCalc.ToString() == strNum)
{
lblIsValid.Text = "Correct";
}
else
{
lblIsValid.Text = "Please enter the correct result";
lblIsValid.ForeColor = Color.DarkRed;
}
}
ASP.net code:
...
<tr>
<td><h2>What is <asp:Label ID="lblFirst" Text="" CssClass="numGen" ClientIDMode="Static" runat="server" /> + <asp:Label ID="lblSecond" Text="" CssClass="numGen" ClientIDMode="Static" runat="server" />?</h2></td>
<td><asp:TextBox ID="tbValidation" ClientIDMode="Static" CssClass="tbTech" runat="server"></asp:TextBox> <asp:Label ID="lblIsValid" runat="server" /></td>
</tr>
<tr>
<td colspan="2" class="setRight">
<asp:Button ID="SubmitForm" ClientIDMode="Static" runat="server" Text="Submit" OnClick="ValidateForm" CssClass="btn" UseSubmitBehavior="false" />
</td>
</tr>
...
I am always seeing Please enter the correct result message.
How can I modify to ensure when the result is entered it works to validate the calculation from code-behind.
It's not clear how you're filling tbValidation but in any case unless you execute your page_load logic only if request it's not postback, variables inFirstOne and inSecondOnewill be overwritten on button click.
It seems you need to have this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
// do this only if it's the first request
rndNum = new Random();
int inFirst = rndNum.Next(1, 51);
int inSecond = rndNum.Next(50, 101);
lblFirst.Text = inFirst.ToString();
inFirstOne = inFirst;
lblSecond.Text = inSecond.ToString();
inSecondOne = inSecond
}
}
int inCalc = Convert.ToInt32(lblFirst.Text) + Convert.ToInt32(lblSecond.Text); worked.
I am loading a Datalist to create the necessary filters (textbox's,dropdown's,checkbox's) for a grid. So far so good, the problem is between postback's.
I understand that every time a postback occours I need to recreate the Datalist with the items, but how can I store the input made by the user on each control?
Imagine that I have created a textbox for filtering a column and the user input "test" on the textbox and click on button that triggers the event to search the value in the gridview.
How can I use (if so) the "viewstate" and when?
Here is the code
Client code:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="imgHelp" />
</Triggers>
<ContentTemplate>
<asp:Panel ID="pnlFilter" runat="server" Width="95%">
<asp:DataList ID="dlFilter" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" OnItemDataBound="dlFilter_ItemDataBound" OnItemCreated="dlFilter_ItemCreated" EnableViewState="true">
<ItemTemplate>
<asp:HiddenField ID="hfFilterName" runat="server" Value='<%# Bind("szFilterName") %>' />
<asp:HiddenField ID="hfFilterType" runat="server" Value='<%# Bind("szFilterObjType") %>' />
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("szFilterFiller") %>' />
</ItemTemplate>
<FooterTemplate>
<table>
<tr>
<td valign="middle" style="width: 120px; text-align: right;">
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Font-Names="Verdana" Font-Size="7pt" OnClick="btnSubmit_Click"
Text="Search" />
</td>
</tr>
</table>
</FooterTemplate>
</asp:DataList>
</asp:Panel>
<br />
<div id="div1" style="overflow: auto; height: auto; width: 97%;">
<asp:GridView ID="gv" runat="server" CssClass="tablecloth-theme" Width="97%" GridLines="Vertical"
AllowSorting="True" AllowPaging="True" PageSize="20" OnPageIndexChanging="gv_PageIndexChanging"
OnSorting="gv_Sorting" SelectedRowStyle-BackColor="Beige" OnSelectedIndexChanged="gv_SelectedIndexChanged">
<HeaderStyle BackColor="#7799AF" Font-Bold="True" Height="20px" Font-Names="Verdana"
Font-Size="7pt" ForeColor="White" HorizontalAlign="Left" />
<Columns>
<asp:CommandField SelectText="Details" ShowSelectButton="True" />
</Columns>
<AlternatingRowStyle BackColor="Gainsboro" />
<SelectedRowStyle BackColor="Beige" />
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Server code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (!scriptManager.IsInAsyncPostBack)
{
DataInfo_Load();
}
//Page_Prepare();
}
catch (Exception ex)
{
ShowError(ex);
}
}
protected void DataInfo_Load()
{
try
{
DataSet_Load();
Filters_Load();
Grid_Load();
if ((int)ViewState["PageStatus"] >= 2)
{
if (ViewState["Saveable"] != null)
btnNew.Visible = (bool)ViewState["Saveable"];
else
btnNew.Visible = true;
}
else
btnNew.Visible = false;
}
catch (Exception ex)
{
throw ex;
}
}
protected void DataSet_Load()
{
try
{
Connection cn = new Connection();
DataSet ds = null;
string Query = hfSelStore.Value;
SqlCommand SQLcmd = new SqlCommand(Query);
SQLcmd.CommandType = System.Data.CommandType.StoredProcedure;
ds = cn.ExecuteSqlCmd(cn.SqlLocalConn, SQLcmd);
ViewState["DataSet"] = ds;
}
catch (Exception ex)
{
throw ex;
}
}
protected void Filters_Load()
{
try
{
if (ViewState["DataSet"] == null)
{
throw new Exception("No DataSet!");
}
DataSet ds = (DataSet)ViewState["DataSet"];
if (ds == null)
{
throw new Exception("DataSet is empty!");
}
if (ds.Tables.Count == 5)
{
//contains filter
pnlFilter.Visible = true;
DataView view = new DataView(ds.Tables[4]);
view.Sort = "lId";
dlFilter.DataSource = view;
dlFilter.DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void dlFilter_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// Retrieve the Label control in the current DataListItem.
HiddenField hfFilterName = (HiddenField)e.Item.FindControl("hfFilterName");
HiddenField filtertype = (HiddenField)e.Item.FindControl("hfFilterType");
if (filtertype != null)
{
DataListItem dlt = ((filtertype.Parent) as DataListItem);
int itemIndex = dlt.ItemIndex;
Label lbl = new Label();
lbl.ID = "lbl";
lbl.Text = hfFilterName.Value;
lbl.Attributes.Add("style", "font-size:7pt; color:#005780; font-weight:bold;");
Control ctr = Control_Create(filtertype.Value);
ctr.ID = "val";
dlt.Controls.Add(new LiteralControl("<table><tr><td valign=\"middle\" style=\"width: 120px; text-align: right;\">"));
dlt.Controls.Add(lbl);
dlt.Controls.Add(new LiteralControl("</td><td>"));
dlt.Controls.Add(ctr);
dlt.Controls.Add(new LiteralControl("</td></tr></table>"));
}
}
}
catch (Exception ex)
{
ShowError(ex);
}
}
protected Control Control_Create(string controlType)
{
Control c = new TextBox();
try
{
if (controlType == "TextBox")
c = new TextBox();
else if (controlType == "CheckBox")
c = new CheckBox();
else if (controlType == "DropDownList")
c = new DropDownList();
else if (controlType == "RadioButton")
c = new RadioButton();
//else if (controlType == "Checkbox")
// c = new TextBox();
//else if (controlType == "Checkbox")
// c = new TextBox();
}
catch (Exception ex)
{
throw ex;
}
return c;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
gv.SelectedIndex = -1;
gv.PageIndex = 0;
Grid_Load();
}
catch (Exception ex)
{
ShowError(ex);
}
}
Can you help me out?
Thanks in advance!
First of all you do not need to load the listview on each postback. The ListView is able to hold the state information during the PostBack. However you should not call the DataBind() function on each postback, if you do so, it will loose the state information. Check where are you binding the ListView
Regarding the dynamic controls added to the ListView, if you add them in the ItemDataBound event as you are doing right now, they retain the state during postback if you call the DataBind() function during first page load i.e under
if(!IsPostBack) code block.
Another point is avoid creating the controls with html in the codebehind as much as possible. You can add these controls in the ItemTemplate and access them in the code behind. If you want to create multiple controls like a table under the list view, you can add a repeater control in the listview's ItemTemplate and bind the repeater in OnItemDataBound event of the ListView.
As I dont see your complete code like Control_Create function, I cannot assist or show code on how you can use Repeater control inside the ListView.
I am having a listview with the following code:-
<asp:ListView ID="ListView1" runat="server"
onitemcommand="ListView1_ItemCommand"
onitemdatabound="ListView1_ItemDataBound"
DataKeyNames="Question_Id" onitemdeleting="ListView1_ItemDeleting"
onitemediting="ListView1_ItemEditing"
onpagepropertieschanging="ListView1_PagePropertiesChanging"
>
<ItemTemplate>
<ul>
<li> <%# Eval("Questiontitle") %>
<%# Eval("Mainquestion")%>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="approve" CommandArgument='<%# Eval("Question_Id") %>'>Approve</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="deny" CommandArgument='<%# Eval("Question_Id") %>'>Deny</asp:LinkButton> </li>
</ul>
</ItemTemplate>
<EmptyDataTemplate>
<br />No data found
</EmptyDataTemplate>
<LayoutTemplate>
<div ID="itemPlaceholderContainer" runat="server" style="font-family: Verdana, Arial, Helvetica, sans-serif;">
<span ID="itemPlaceholder" runat="server" />
</div>
<div style="text-align: center;background-color: #CCCCCC;font-family: Verdana, Arial, Helvetica, sans-serif;color: #000000;">
</div>
<asp:DataPager ID="dpListView" runat="server" PageSize="2" OnPreRender="ListView1_PreRender">
<Fields>
<asp:NumericPagerField ButtonType="Link"/>
</Fields>
</asp:DataPager>
</LayoutTemplate>
</asp:ListView>
Now my cs code is given as
var cat = DropDownList1.SelectedValue;
var DBL = Getdata.GetDataFromSP("Spgetquestionbycategoryid", new object[,] { { "cat" }, { cat } });
if (DBL.Rows[e.Item.DataItemIndex]["Approval"].ToString() == "True")
{
LinkButton btn = ListView1.Controls[e.Item.DataItemIndex].FindControl("LinkButton1") as LinkButton;
LinkButton btn1 = ListView1.Controls[e.Item.DataItemIndex].FindControl("LinkButton2") as LinkButton;
btn.BackColor = System.Drawing.Color.Green;
btn1.BackColor = System.Drawing.Color.Transparent;
}
else if (DBL.Rows[e.Item.DataItemIndex]["Approval"].ToString() == "")
{
LinkButton btn = ListView1.Controls[e.Item.DataItemIndex].FindControl("LinkButton2") as LinkButton;
LinkButton btn1 = ListView1.Controls[e.Item.DataItemIndex].FindControl("LinkButton1") as LinkButton;
btn.BackColor = System.Drawing.Color.Transparent;
btn1.BackColor = System.Drawing.Color.Transparent;
}
else if (DBL.Rows[e.Item.DataItemIndex]["Approval"].ToString() == "False")
{
LinkButton btn = ListView1.Controls[e.Item.DataItemIndex].FindControl("LinkButton2") as LinkButton;
LinkButton btn1 = ListView1.Controls[e.Item.DataItemIndex].FindControl("LinkButton1") as LinkButton;
btn.BackColor = System.Drawing.Color.Red;
btn1.BackColor = System.Drawing.Color.Transparent;
}
Now at this place when i try to find out my linkbutton it is giving me null object reference error.
As i have some conditions that are to be applied to the link button.
If i remove the datapaging from the same.I dont get any error and it is working perfectly.
please suggest.
You should DataBind your ListView again in PagePropertiesChanged event:
protected void ListView_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
ListView1.DataSource = getdataSource();
ListView1.DataBind();
}
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
LinkButton btn1 = (LinkButton)e.Item.FindControl("LinkButton1");
var approveDeny = false;
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
System.Boolean.TryParse(DataBinder.Eval(dataItem.DataItem, "ApproveOrDeny").ToString(), out approveDeny);
if (approveDeny)
{
btn1.BackColor = System.Drawing.Color.Green;
btn1.BackColor = System.Drawing.Color.Transparent;
}
else if (!approveDeny)
{
btn1.BackColor = System.Drawing.Color.Blue;
btn1.BackColor = System.Drawing.Color.Transparent;
}
else
{
btn1.BackColor = System.Drawing.Color.Red;
btn1.BackColor = System.Drawing.Color.Transparent;
}
}
}