finding link button at the time of item data bound - c#

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;
}
}
}

Related

Asp.net how to maintain radio button selection when using datapager

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();
}

How to get value from dynamically created radiobuttonlist using listview?

I am trying to create a dynamic Multiple-choice Question Quiz, where we have different categories in which there are multiple questions with their individual options. I need to store the selected option as per the user.
Below is the aspx code which I am using to bind the data:
<div id="contact-form">
<input type="text" class="form-control form-control-custom" tabindex="-1"
id="text-field" name="text-field">
<asp:ListView ID="lv_cat" runat="server" OnItemDataBound="lv_cat_ItemDataBound">
<EmptyDataTemplate></EmptyDataTemplate>
<ItemTemplate>
<h4 style="border: 2px solid #000; background-color: #ffd281;"><%# Eval("Cat_name") %></h4>
<asp:Label ID="lbl_Cat_id" runat="server" Text='<%# Eval("cat_id") %>' hidden="true"></asp:Label>
<asp:ListView ID="Lv_question" runat="server" OnItemDataBound="Lv_question_ItemDataBound">
<EmptyDataTemplate></EmptyDataTemplate>
<ItemTemplate>
<div class="row">
<p style="text-align: left; font-weight: 600;"><%# Eval("Question") %></p>
<asp:Label ID="lbl_Q_Id" runat="server" Text='<%# Eval("Q_id") %>' hidden="true"></asp:Label>
<asp:RadioButtonList ID="Rbl_options" runat="server" Style="text-align: left;">
</asp:RadioButtonList>
</div>
</ItemTemplate>
</asp:ListView>
</ItemTemplate>
</asp:ListView>
</div>
<!-- /End Contact Form -->
<br />
<!-- Submit Button -->
<div class="btn-row">
<div class="form-group">
<asp:Button ID="Button2" class="btn btn-dark" runat="server" Text=" Submit"></asp:Button>
</div>
</div>
And the below is the aspx.cs code for binding the data.
Now I want to fetch the details submitted by the user.
private void getProjectdetails()
{
try
{
BAL_Projects balprojects = new BAL_Projects();
balprojects.P_id = p_id;
ds = balprojects.get_data_By_project_Id(str);
if (ds.Tables[0].Rows.Count > 0)
{
lbl_Project.Text = ds.Tables[0].Rows[0]["pname"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void lv_cat_ItemDataBound(object sender, ListViewItemEventArgs e)
{
try
{
Label cat_id = (Label)e.Item.FindControl("lbl_Cat_id");
balQuestions = new BAL_Questions();
balQuestions.Cat_id = cat_id.Text;
ds1 = balQuestions.get_data_questions_By_category_ID(str);
ListView ListView2 = e.Item.FindControl("Lv_question") as ListView;
if (ds1.Tables[0].Rows.Count > 0)
{
ListView2.DataSource = ds1.Tables[0];
ListView2.DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void Lv_question_ItemDataBound(object sender, ListViewItemEventArgs e)
{
try
{
Label Q_id = (Label)e.Item.FindControl("lbl_Q_Id");
BAL_options bal_options = new BAL_options();
ds = bal_options.get_options_for_Question(str, Q_id.Text.ToString());
if (ds.Tables[0].Rows.Count > 0)
{
RadioButtonList rbl_1 = (RadioButtonList)e.Item.FindControl("Rbl_options");
rbl_1.DataSource = ds;
rbl_1.DataTextField = "answers";
rbl_1.DataValueField = "A_id";
rbl_1.DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}
private void getCategorydata()
{
try
{
BAL_category bal_category = new BAL_category();
bal_category.p_id = p_id;
ds = bal_category.get_data_category_By_Project_ID(str);
if (ds.Tables[0].Rows.Count > 0)
{
lv_cat.DataSource = ds;
lv_cat.DataBind();
}
}
catch (Exception ex) { }
}
I also tried the below code:
public void btnsubmit_Click(object sender, EventArgs e)
{
try
{
foreach (ListViewItem item in lv_cat.Items)
{
ListView listQ = (ListView)item.FindControl("lv_Question");
foreach (ListViewItem item1 in listQ.Items)
{
Label QID = (Label)item1.FindControl("lbl_Q_Id");
RadioButtonList rbl1 = (RadioButtonList)item1.FindControl("rbl_options");
string test = rbl1.SelectedValue.ToString();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
You basically do the same as when you are binding data to the Rbl_options RadioButtonList in the ListView ItemDataBound. On the button click loop all the items in the ListView, locate the RadioButton within the item and use FindControl.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//bind the datasource for the listview
Lv_question.DataSource = source;
Lv_question.DataBind();
}
}
protected void Lv_question_ItemDataBound(object sender, ListViewItemEventArgs e)
{
//use findcontrol to locate the radiobuttonlist and cast is back
RadioButtonList rbl = e.Item.FindControl("Rbl_options") as RadioButtonList;
//add some dummy listitems
for (int i = 0; i < 3; i++)
{
rbl.Items.Add(new ListItem() { Text = "Item " + i, Value = i.ToString() });
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//loop all the items in the listview
foreach (var item in Lv_question.Items)
{
//use findcontrol again to locate the radiobuttonlist in the listview item
RadioButtonList rbl = item.FindControl("Rbl_options") as RadioButtonList;
//show results
Label1.Text += rbl.SelectedValue + "<br>";
}
}
The aspx to make the demo complete
<asp:ListView ID="Lv_question" runat="server" OnItemDataBound="Lv_question_ItemDataBound">
<ItemTemplate>
<asp:RadioButtonList ID="Rbl_options" runat="server"></asp:RadioButtonList>
</ItemTemplate>
</asp:ListView>

DataList loaded dynamically, how to store values inside between postbacks

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.

Insert <p> tags with C#?

This is sort of a weird question, but is there a way to insert <p> tags around some imported text? I have a list of blog entries, each of which comes from its own source (I think it's a copy-paste job into Sitecore). All entries have an "Introduction" which is the blurb about the article. Some of these has <p> tags enclosing them and others do not (I'm not sure why and I can't change the source material--I can only have control on how it looks when it comes into the blog listing page) I'm thinking there should be a check to see if they do exist first, although I am not sure how that could be done.
This is the front end for the blog listing:
<asp:GridView ID="EntryList" runat="server" OnItemDataBound="EntryDataBound" AllowPaging="true" PageSize="3" AutoGenerateColumns="false" EnablePersistedSelection="true" DataKeyNames="EntryID" OnPageIndexChanging="grdTrades_PageIndexChanging" GridLines="None" PagerSettings-Position="TopAndBottom" CssClass="mGrid" pagerstyle-cssclass="pagination" rowstyle-cssclass="norm" alternatingrowstyle-cssclass="altColor" width="100%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<li class="wb-entry-list-entry" >
<div class="imgOuter">
<div class="imgInner">
<asp:Image runat="server" ID="EntryImage" CssClass="wb-image" ImageUrl='<%# Eval("Image") %>' />
</div>
</div>
<div class="outer">
<div class="wb-entry-detail" >
<h2>
<%# Eval("Title") %>
</h2>
<div class="wb-details">
<%# Eval("EntryDate") %>
<%# Eval("Author") %><br />
<%# Eval("AuthorTitle") %>
</div>
<%# Eval("Introduction") %>
<asp:HyperLink ID="BlogPostLink" runat="server" CssClass="wb-read-more" NavigateUrl='<%# Eval("EntryPath") %>'><%# Sitecore.Globalization.Translate.Text("READ_MORE")%></asp:HyperLink>
<asp:PlaceHolder ID="CommentArea" runat="server">
<span class="wb-comment-count">
</span>
</asp:PlaceHolder>
</div>
</div>
</li>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<%#Sitecore.Globalization.Translate.Text("NO_POSTS_FOUND")%>
</EmptyDataTemplate>
And this is the codebehind:
Database db = Sitecore.Context.Database;
protected const string DEFAULT_POST_TEMPLATE = "/layouts/WeBlog/PostListEntry.ascx";
protected Size m_imageMaxSize = Size.Empty;
protected void grdTrades_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
EntryList.PageIndex = e.NewPageIndex;
string tag = Request.QueryString["tag"];
BindEntries(tag);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string requestedToShowStr = Request.QueryString["count"] ?? "0";
int requestedToShow = 0;
int.TryParse(requestedToShowStr, out requestedToShow);
string startIndexStr = Request.QueryString["startIndex"] ?? "0";
int startIndex = 0;
int.TryParse(startIndexStr, out startIndex);
string tag = Request.QueryString["tag"];
Item CurrentItem = Sitecore.Context.Item;
BindEntries(tag);
string blogUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item);
}
}
protected void BindEntries(string tag)
{
DataSet ds = new DataSet();
DataTable ResultTable = ds.Tables.Add("EntryTable");
ResultTable.Columns.Add("EntryID", Type.GetType("System.String"));
ResultTable.Columns.Add("EntryPath", Type.GetType("System.String"));
ResultTable.Columns.Add("Title", Type.GetType("System.String"));
ResultTable.Columns.Add("EntryDate", Type.GetType("System.String"));
ResultTable.Columns.Add("Author", Type.GetType("System.String"));
ResultTable.Columns.Add("AuthorTitle", Type.GetType("System.String"));
ResultTable.Columns.Add("Introduction", Type.GetType("System.String"));
ResultTable.Columns.Add("Image", Type.GetType("System.String"));
Item CurrentItem = Sitecore.Context.Item;
Item BlogStart = ScHelper.FindAncestor(CurrentItem, "BlogHome");
Item[] EntryArray = null;
if (tag == "")
EntryArray = BlogStart.Axes.SelectItems(#"child::*[##templatename='Folder']/*[##templatename='Folder']/*[(##templatename='BlogEntry' ) ]");
else
EntryArray = BlogStart.Axes.SelectItems(#"child::*[##templatename='Folder']/*[##templatename='Folder']/*[(##templatename='BlogEntry' and contains(#tags,'" + tag + "' )) ]");
ArrayList PostList = new ArrayList();
if (EntryArray != null)
{
foreach (Item EntryItem in EntryArray)
{
if (EntryItem.Fields["Post Date"].Value != "")
{
BlogEntryProcessor.BlogEntrys obj1 = new BlogEntryProcessor.BlogEntrys();
obj1.Description = EntryItem.Fields["Introduction"].Value;
obj1.Guid = EntryItem.ID.ToString();
obj1.Link = ScHelper.GetPath(EntryItem);
obj1.PostDate = formatDateCmp(EntryItem.Fields["Post Date"].Value);
obj1.Title = EntryItem.Fields["Title"].Value;
PostList.Add(obj1);
}
}
PostList.Sort();
PostList.Reverse();
foreach (BlogEntryProcessor.BlogEntrys obj in PostList)
{
DataRow dr = ResultTable.NewRow();
Item BlogEntry = db.Items[obj.Guid];
dr["EntryID"] = obj.Guid;
dr["EntryPath"] = ScHelper.GetPath(BlogEntry);
dr["Title"] = BlogEntry.Fields["Title"].Value;
dr["EntryDate"] = GetPublishDate(BlogEntry);
dr["Author"] = GetAuthor(BlogEntry);
dr["AuthorTitle"] = GetAuthorTitle(BlogEntry);
dr["Introduction"] = BlogEntry.Fields["Introduction"].Value;
//TODO: get Default Image
string EntryThumbImage = BlogEntry.Fields["Thumbnail Image"].Value;
string EntryImage = BlogEntry.Fields["Image"].Value;
string ArtImage = "http://fpoimg.com/140x140";
if (EntryImage != "")
{
Sitecore.Data.Fields.XmlField fileField = BlogEntry.Fields["Image"];
ArtImage = "/" + ScHelper.GetCorrectFilePath(fileField);
}
else if (EntryThumbImage != "")
{
Sitecore.Data.Fields.XmlField fileField = BlogEntry.Fields["Thumbnail Image"];
ArtImage = "/" + ScHelper.GetCorrectFilePath(fileField);
}
dr["Image"] = ArtImage;
ResultTable.Rows.Add(dr);
}
EntryList.DataSource = ds;
EntryList.DataMember = "EntryTable";
EntryList.DataBind();
}
}
protected string GetAuthorTitle(Item entry)
{
string OutName = "";
string AuthorID = entry.Fields["Author"].Value;
Item AuthorItem = db.Items[AuthorID];
if (AuthorItem != null)
OutName = AuthorItem.Fields["Author Title"].Value;
return OutName;
}
protected string GetAuthor(Item entry)
{
string OutName = "";
string AuthorID = entry.Fields["Author"].Value;
Item AuthorItem = db.Items[AuthorID];
if (AuthorItem != null)
OutName = string.Format("<br />By <a href='{0}'>{1}</a>", ScHelper.GetPath(AuthorItem), AuthorItem.Fields["Author Name"].Value);
return OutName;
}
protected string GetPublishDate(EntryItem CurrentEntry)
{
string pDate = GOJOHelper.FormatDate(((Item)CurrentEntry).Fields["Post Date"].Value);
return pDate;
}
protected void EntryDataBound(object sender, ListViewItemEventArgs args)
{
if (args.Item.ItemType == ListViewItemType.DataItem)
{
var dataItem = args.Item as ListViewDataItem;
var control = dataItem.FindControl("EntryImage");
if (control != null)
{
var imageControl = control as global::Sitecore.Web.UI.WebControls.Image;
imageControl.MaxWidth = m_imageMaxSize.Width;
imageControl.MaxHeight = m_imageMaxSize.Height;
var entry = dataItem.DataItem as EntryItem;
if (entry.ThumbnailImage.MediaItem == null)
imageControl.Field = "Image";
}
}
}
//string to use to sort the dates - must have 2 digit for month and day
private string formatDateCmp(string date)
{
// Set the dateResult for the TryParse
DateTime dateResult = new DateTime();
// Split the date up. ie. 20090101T000000
string[] TempStr = date.Split('T');
// Set the date to the characters before the T
date = TempStr[0];
// Insert a slash after the first 4 characters and after 7
date = date.Insert(4, "/").Insert(7, "/");
return date;
}
You can always do something like...
dr["Introduction"] = BlogEntry.Fields["Introduction"].Value
.Replace("\n\n", "</p><p>");
... or whichever escape characters are being used to denote separation of paragraphs in your source data. Alternatively, you could use Regex utilities. See Example 3 in this article for further reference.
Firstly in your GridView you've got
OnItemDataBound="EntryDataBound"
OnItemDataBound isn't an event of GridView I'm a little surprised that works!
Use
OnRowDataBound="EntryList_RowDataBound"
This is my common pattern for GridView's and Repeaters, noticed I've used a Literal control in the HTML, I'm not a mega fan of Eval! Also note that if (dataItem == null) just if there's a data item for that row, RowTypes like header and footer don't have any data, it's easier than the typical if(e.Row.RowType == DataControlRowType.Header) etc
<asp:GridView ID="EntryList" runat="server" OnRowDataBound="EntryList_RowDataBound" AllowPaging="true" PageSize="3" AutoGenerateColumns="false" EnablePersistedSelection="true" DataKeyNames="EntryID" OnPageIndexChanging="grdTrades_PageIndexChanging" GridLines="None" PagerSettings-Position="TopAndBottom" CssClass="mGrid" PagerStyle-CssClass="pagination" RowStyle-CssClass="norm" AlternatingRowStyle-CssClass="altColor" Width="100%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<li class="wb-entry-list-entry">
<div class="imgOuter">
<div class="imgInner">
<asp:Image runat="server" ID="EntryImage" CssClass="wb-image" ImageUrl='<%# Eval("Image") %>' />
</div>
</div>
<div class="outer">
<div class="wb-entry-detail">
<h2>
<%# Eval("Title") %>
</h2>
<div class="wb-details">
<%# Eval("EntryDate") %>
<%# Eval("Author") %><br />
<%# Eval("AuthorTitle") %>
</div>
<asp:Literal runat="server" ID="IntroductionLiteral"/>
<asp:HyperLink ID="BlogPostLink" runat="server" CssClass="wb-read-more" NavigateUrl='<%# Eval("EntryPath") %>'><%# Sitecore.Globalization.Translate.Text("READ_MORE")%></asp:HyperLink>
<asp:PlaceHolder ID="CommentArea" runat="server">
<span class="wb-comment-count"></span>
</asp:PlaceHolder>
</div>
</div>
</li>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<%#Sitecore.Globalization.Translate.Text("NO_POSTS_FOUND")%>
</EmptyDataTemplate>
</asp:GridView>
.cs file
protected void EntryList_RowDataBound(object sender, GridViewRowEventArgs e)
{
var dataItem = e.Row.DataItem as EntryItem;
if (dataItem == null)
return;
var imageControl = e.Row.FindControl("EntryImage") as global::Sitecore.Web.UI.WebControls.Image;
var introductionControl = e.Row.FindControl("IntroductionLiteral") as Literal;
if (imageControl == null || introduction == null)
return;
imageControl.MaxWidth = m_imageMaxSize.Width;
imageControl.MaxHeight = m_imageMaxSize.Height;
if (dataItem.ThumbnailImage.MediaItem == null)
imageControl.Field = "Image";
if (!string.IsNullOrEmpty(data["introduction"]))
introductionControl.Text = string.Format("<p>{0}</p>", data["introduction"].ToString().Replace("\n\r", "</p><p>"));
}
Also if you've got a list of Sitecore objects why don't you just bind that to the GridView, then in your RowDataBound method get the item back
var dataItem = e.Row.DataItem as Item;
and then do the logic in the BindEntries method in there, would prob be cleaner code and you wouldn't have to use stupid DataSets! Just an idea.

Radiobuttons in different groups getting enabled on PostBack

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;
}
}

Categories