I have 2 dropdownlist on my web form and the second one is synchronised with the first one based upon what value has been chosen.
Everything works well between the 2 of them and am able to use the values from them to carry out my function.
However the first dropdownlist seems to have an effect on my repeater and paginations. Basically it keeps incrementing the pageddatesource and clears the repeater of any data ?
The SelectedIndexChanged is only meant to update the update.panel1 where the second dropdownlist is but then am not sure how it further increments the page numbers and removes data from repeater?
Here is the front end with the dropdownlists.
<section id="section-search">
<div class="fleft">
Start Date:
<asp:TextBox runat="server" ID="txtStartDate" CssClass="txt txt-sml"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="calStartDate" runat="server" PopupPosition="Right" Animated="true" TargetControlID="txtStartDate" />
End Date:
<asp:TextBox runat="server" ID="txtEndDate" CssClass="txt txt-sml"></asp:TextBox>
<ajaxToolkit:CalendarExtender runat="server" ID="calEndDate" PopupPosition="Right" Animated="true" TargetControlID="txtEndDate"></ajaxToolkit:CalendarExtender>
<hr />
Product Class:
<asp:DropDownList ID="drpProductClass" runat="server" Width="230px" OnSelectedIndexChanged="drpProductClass_SelectedIndexChanged" AutoPostBack="true" />
<hr />
<asp:UpdatePanel ID="updatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
Product:
<asp:DropDownList ID="drpProduct" runat="server" Width="230px" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="fright">
<asp:Button runat="server" ID="btnFilter" Text="Search" CssClass="submit" OnClick="btnFilter_Click"/>
</div>
</section>
<section id="section-title">
<h1>Order Search</h1><h2></h2>
</section>
<section class="info-strip tr">
<asp:Literal ID="litResults" runat="server"></asp:Literal>
</section>
<section class="track-table">
<asp:Literal runat="server" ID="litMessage" Visible="false" Text="<div class='wysiwyg'><p>You currently have no orders...</p></div>"></asp:Literal>
<asp:PlaceHolder runat="server" ID="phOrders">
<%--<table>
<thead>
</thead>
<tbody>--%>
<asp:Repeater ID="rprOrders" runat="server" OnItemCommand="rprOrders_ItemCommand" >
Here is my Code behind
protected void SetupControl()
{
if (this.StopProcessing)
{
// Do not process
}
else
{
if (CMSContext.ViewMode == ViewModeEnum.LiveSite)
{
if(!Page.IsPostBack)
{
PopulateProductClass();
PopulateProduct();
PopulateOrders();
}
}
}
}
protected void drpProductClass_SelectedIndexChanged(object sender, EventArgs e)
{
CustomTableItemProvider ctip = new CustomTableItemProvider();
UserInfo user = CooneenHelper.GetUserImpersonisationUser();
QueryDataParameters qdp = new QueryDataParameters();
qdp.Add("#UserID", user.UserID);
DataSet ds = gc.ExecuteQuery("CN_GetEmpIDByUID", qdp, QueryTypeEnum.StoredProcedure, true);
int emplID = Convert.ToInt32(ds.Tables[0].Rows[0]["UserEmployeeID"].ToString());
if (drpProductClass.SelectedValue.ToString() != "0")
{
QueryDataParameters qdp2 = new QueryDataParameters();
qdp2.Add("#WR_ClassID", Convert.ToInt32(drpProductClass.SelectedValue.ToString()));
qdp2.Add("#UserEmployeeID", emplID);
DataSet ds2 = gc.ExecuteQuery("CN_OrdersGetProductByClassID", qdp2, QueryTypeEnum.StoredProcedure, true);
drpProduct.ClearSelection();
drpProduct.DataSource = ds2.Tables[1];
drpProduct.DataTextField = "ProductName";
drpProduct.DataValueField = "SKUNumber";
drpProduct.DataBind();
drpProduct.Items.Insert(0, new ListItem("-- Select Product --", "0"));
updatePanel1.Update();
}
else
{
drpProduct.ClearSelection();
PopulateProduct();
}
}
private void PopulateOrders()
{
CustomerInfo ki = CustomerInfoProvider.GetCustomerInfoByUserID(CooneenHelper.GetUserImpersonisationID());
int nKustomerID = ki.CustomerID;
DataTable dts = new DataTable();
dts.Columns.Add("OrderDate", typeof(string));
dts.Columns.Add("OrderNumber", typeof(string));
dts.Columns.Add("OrderItemSKUName", typeof(string));
dts.Columns.Add("OrderItemSKUID", typeof(string));
dts.Columns.Add("OrderItemStatus", typeof(string));
dts.Columns.Add("OrderItemUnitCount", typeof(string));
QueryDataParameters qdp = new QueryDataParameters();
qdp.Add("#CustomerID", nKustomerID);
DataSet ds = gc.ExecuteQuery("CN_OrderList", qdp, QueryTypeEnum.StoredProcedure, true);
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow drNew = dts.NewRow();
drNew["OrderDate"] = ValidationHelper.GetDateTime(dr["OrderDate"], DateTime.Now).ToShortDateString();
drNew["OrderNumber"] = dr["OrderNumber"].ToString();
drNew["OrderItemSKUName"] = dr["OrderItemSKUName"].ToString();
drNew["OrderItemSKUID"] = dr["OrderItemSKUID"].ToString();
drNew["OrderItemStatus"] = dr["OrderItemStatus"].ToString();
drNew["OrderItemUnitCount"] = dr["OrderItemUnitCount"].ToString();
dts.Rows.Add(drNew);
}
PagedDataSource pds = new PagedDataSource();
pds.DataSource = dts.DefaultView;
//DataView view = dts.DefaultView;
//allow paging, set page size, and current page
pds.AllowPaging = true;
pds.PageSize = PerPage;
pds.CurrentPageIndex = CurrentPage;
//show # of current page in label
if (pds.PageCount > 1) litResults.Text += " - Showing page " + (CurrentPage + 1).ToString() + " of " + pds.PageCount.ToString();
//disable prev/next buttons on the first/last pages
btnPrev.Enabled = !pds.IsFirstPage;
btnNext.Enabled = !pds.IsLastPage;
rprOrders.Visible = true;
rprOrders.DataSource = pds;
rprOrders.DataBind();
}
We had a similar problem and could never figure out the root cause of it, we chalked it up to a bug in WebForms. But we were able to get around the problem by setting ClientIDMode="AutoID" for the control or page, we ended up setting our entire site that way cause we found problems that it happened to solve. Let me know if this works for you too. Wish I could be of greater help.
Related
I am designing a web page in asp.net C# named "myprofile". The structure is as follows from top to bottom: file upload control(for logo), drop down (for hotel type), a rich text box (for contact information - extra: bold, italics, hyperlink etc features), drop down (for location).
My problem is maintaining the values of file upload control and rich text box on postback. Also I am unable to insert the values in database as nothing is happening. I tried many things. Finally, I set my design as follows:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset style="width:30%">
<legend>Update Panel-1</legend>
<br />(Type of Hotel)<br /><br />
<asp:DropDownList ID="DropDownTypeOfHotel" runat="server" CssClass="cssdropdown"></asp:DropDownList>
<br />(Contact Information Here)<br /><br />
<asp:TextBox ID="RichTextBoxContactInfo" runat="server"></asp:TextBox>
<br />(Location)<br /><br />
<asp:DropDownList ID="DropDownListLocation" runat="server" CssClass="cssdropdown"></asp:DropDownList>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset style="width:30%">
<legend>Update Panel-2</legend>
<asp:Label ID="Label1" runat="server" Text="" ForeColor="Red"></asp:Label>
<br /><br />
<asp:Button ID="btnUpdate2" runat="server" Text="Update Both Panels" OnClick="btnUpdate2_Click" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
My code for the same lies here:-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadHotelType();
}
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
protected void btnUpdate2_Click(object sender, EventArgs e)
{
if (DropDownTypeOfHotel.SelectedIndex > 0)
{
if (DropDownListLocation.SelectedIndex > 0)
{
if (!string.IsNullOrEmpty(RichTextBoxContactInfo.Text))
{
Label1.Text = "Cool!";
insert();
}
else
{
Label1.Text = "Kindly add contact info!";
}
}
else
{
Label1.Text = "Kindly select location!";
}
}
else
{
Label1.Text = "Kindly select type of hotel!";
}
}
public void loadHotelType()
{
DropDownTypeOfHotel.Items.Insert(0, "--Select Type of Hotel/Supplier--");
DropDownTypeOfHotel.Items.Insert(1, "2 star");
DropDownTypeOfHotel.Items.Insert(2, "3 star");
DropDownTypeOfHotel.Items.Insert(3, "5 star");
DropDownListLocation.Items.Insert(0, "--Select Location of Hotel/Supplier--");
DropDownListLocation.Items.Insert(1, "Canada");
DropDownListLocation.Items.Insert(2, "USA");
DropDownListLocation.Items.Insert(3, "LA");
}
public void insert()
{
int img_logo = 0;
static byte[] btlogo_img;
if (FileUpload1.PostedFile.ContentLength != 0)
{
btlogo_img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile up1 = FileUpload1.PostedFile;
up1.InputStream.Read(btlogo_img, 0, (int)FileUpload1.PostedFile.ContentLength);
img_logo = 1;
}
if (img_logo == 1)
{
con1.Close();
con1.Open();
SqlCommand cmd = new SqlCommand("insert into file values('" + FileUpload1.PostedFile.FileName + "','" + btlogo_img + "')", con1);
cmd.ExecuteNonQuery();
con1.Close();
}
else
{
Label1.Text = "Kindly select logo!";
}
}
Kindly suggest me with the same.
The easiest solution I found was to keep the controls, that loses value on postback, outside update panel and keep all other controls inside update panel.
It really worked for me!
I have two GridView and i want display data from two DataTables. There is my GridViews code in aspx file :
<div class="col-sm-5">
<div class="col-sm-6">
<asp:GridView ID="gvSource" runat="server" ShowHeaderWhenEmpty="true" CssClass="drag_drop_grid GridSrc" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>Miejsca (wybór)</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNazwa" runat="server" Text='<%# Eval("Nazwa") %>' />
<asp:HiddenField ID="IDVal" ClientIDMode="Static" runat="server" Value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="col-sm-6 pull-left">
<asp:GridView ID="gvDest" runat="server" ShowHeaderWhenEmpty="true" EmptyDataText="No data to display" CssClass="drag_drop_grid GridDest" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>Miejsca (należące do wycieczki)</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNazwa" runat="server" Text='<%# Eval("Nazwa") %>' />
<asp:HiddenField ID="IDVal" ClientIDMode="Static" runat="server" Value='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
There is my Code-Behind :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
recID = int.Parse(Request.QueryString["id"]);
if (recID > 0)
{
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)), new DataColumn("Nazwa", typeof(string)) });
dt2.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)), new DataColumn("Nazwa", typeof(string)) });
Miejsca ms = new Miejsca();
Hashtable hs = new Hashtable();
foreach (var lst in ms.PobierzMiejscaLista(hs))
{
dt.Rows.Add(lst.Id , lst.Nazwa);
}
gvSource.UseAccessibleHeader = true;
gvSource.DataSource = dt;
gvSource.DataBind();
dt.Rows.Clear();
dt.Rows.Add();
Wycieczka w = (new Wycieczki()).PobierzWycieczke(recID);
foreach (var lst in w.Miejsca)
{
Miejsce tempM = (new Miejsca()).PobierzMiejsce(lst.Id_Miejsce.Id);
dt2.Rows.Add(tempM.Id, tempM.Nazwa);
}
int ilosc = dt2.Rows.Count;
//gvDest.UseAccessibleHeader = true;
gvDest.DataSource = dt2;
gvDest.DataBind();
//Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "TablicaMiejsc", "loadPlacesIntoTrip("+recID+");", true);
}
}
else
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id"), new DataColumn("Nazwa") });
Miejsca ms = new Miejsca();
Hashtable hs = new Hashtable();
foreach (var lst in ms.PobierzMiejscaLista(hs))
{
//listMiejsc.Add(lst);
dt.Rows.Add(lst.Id, lst.Nazwa);
}
gvSource.UseAccessibleHeader = true;
gvSource.DataSource = dt;
gvSource.DataBind();
dt.Rows.Clear();
dt.Rows.Add();
gvDest.DataSource = new List<String>();
gvDest.DataBind();
recID = 0;
}
}
}
And i don't know why but only one GridView (gvSource) display data.
Second GridView (gvDest) not display data.
When i debug code i see both DataTables have data. Both GridView DataSources have data too. But only one GridView display data.
I use Nhibernate to lazy load (w.Miejsca) collection and get objects like "Miejsce" or "Wycieczka" from database. Also I use JQuery and JQuery UI to make sortable GridViews.
Sorry for my bad english, it's not my native language.
I hope you can help me :)
UPDATE
Finally I found what is responsible for this situation.
Because of my stupidity i lost a lot of time :)
This line of code is removed the items from GridView:
$("[id*=gvDest] tr:not(tr:first-child)").remove();
Thank you for your advice.
The problem was solved.
Please remove ClientIDMode="Static" from second grid view and check it.
<asp:Repeater ID="RepCourse" runat="server">
<ItemTemplate>
<div style="width:400px"></div>
<div class="course" style="float: left; margin-left: 100px; margin-top: 100px">
<div class="image">
<asp:Image ID="imgteacher" runat="server" Height="150" Width="248" ImageUrl='<%# "ShowImage.ashx?id="+ DataBinder.Eval(Container.DataItem, "CourseID") %>'/>
</div>
<div style="margin-left: 3px; width: 250px">
<div class="name">
<asp:Label runat="server" ID="lblname" Text='<%#Eval("CourseName") %>'></asp:Label>
</div>
<div style="height: 13px"></div>
<div id="teacher">
<%#Eval("UserName") %>
</div>
</div>
<div style="height: 4px"></div>
<div class="date">
<div id="datebegin">
<asp:Label ID="lbldatebegin" runat="server" Text='<%#Eval("BeginDate") %>'></asp:Label>
</div>
<div id="dateend">
<asp:Label ID="lbldateend" runat="server" Text='<%#Eval("ClosingDate") %>'></asp:Label>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
In my project Repeater Control works fine. And now I need pagination for replacing those data. But I don't have any information about this. May be someone give me advice about this issue.
As shown below picture.
There's no built-in pagination in the Repeater control, but based on this article, you can achieve pagination in the Repeater control by creating another Repeater control for pages and use PagedDataSource as it's source.
First, add this to your markup:
<div style="overflow: hidden;">
<asp:Repeater ID="rptPaging" runat="server" OnItemCommand="rptPaging_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="btnPage"
style="padding:8px;margin:2px;background:#ffa100;border:solid 1px #666;font:8pt tahoma;"
CommandName="Page" CommandArgument="<%# Container.DataItem %>"
runat="server" ForeColor="White" Font-Bold="True">
<%# Container.DataItem %>
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</div>
Next, add the following property in your code behind:
//This property will contain the current page number
public int PageNumber
{
get
{
if (ViewState["PageNumber"] != null)
{
return Convert.ToInt32(ViewState["PageNumber"]);
}
else
{
return 0;
}
}
set { ViewState["PageNumber"] = value; }
}
Finally add the following methods:
protected void Page_Load(object sender, EventArgs e)
{
BindRepeater();
}
private void BindRepeater()
{
//Do your database connection stuff and get your data
SqlConnection cn = new SqlConnection(yourConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
SqlDataAdapter ad = new SqlDataAdapter(cmd);
cmd.CommandText = "Select * from YourTable";
//save the result in data table
DataTable dt = new DataTable();
ad.SelectCommand = cmd;
ad.Fill(dt);
//Create the PagedDataSource that will be used in paging
PagedDataSource pgitems = new PagedDataSource();
pgitems.DataSource = dt.DefaultView;
pgitems.AllowPaging = true;
//Control page size from here
pgitems.PageSize = 4;
pgitems.CurrentPageIndex = PageNumber;
if (pgitems.PageCount > 1)
{
rptPaging.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i <= pgitems.PageCount - 1; i++)
{
pages.Add((i + 1).ToString());
}
rptPaging.DataSource = pages;
rptPaging.DataBind();
}
else
{
rptPaging.Visible = false;
}
//Finally, set the datasource of the repeater
RepCourse.DataSource = pgitems;
RepCourse.DataBind();
}
//This method will fire when clicking on the page no link from the pager repeater
protected void rptPaging_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
{
PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
BindRepeater();
}
Please give it a try and if you faced any issue just inform me.
Edit: Alternative Solution
Another excellent solution can be found Here, this solution includes the Navigation buttons of pages. You'll need to download files from that link to see a functional pagination and just replace the DataList control with your Repeater control.
Hope this helps.
I have a standard Repeater and all I want to do is add paging to it and I keep getting the error listed in the title. Here is what my error points to
private void ItemsGet()
{
// Read sample item info from XML document into a DataSet
DataSet Items = new DataSet();
Items.ReadXml(MapPath("Items.xml"));
// Populate the repeater control with the Items DataSet
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = Items.Tables[0].DefaultView;
objPds.AllowPaging = true;
objPds.PageSize = 3;
objPds.CurrentPageIndex = CurrentPage;
lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of "
+ objPds.PageCount.ToString();
// Disable Prev or Next buttons if necessary
cmdPrev.Enabled = !objPds.IsFirstPage;
cmdNext.Enabled = !objPds.IsLastPage;
Repeater1.DataSource = objPds;
Repeater1.DataBind();
}
for those that will ask I will post my repeater
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="myFunction">
<HeaderTemplate>
</HeaderTemplate>
<AlternatingItemTemplate>
</AlternatingItemTemplate>
<ItemTemplate>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
<tr>
<td><asp:label id="lblCurrentPage" runat="server"></asp:label></td>
</tr>
I believe that your're setting the DataSourceID="SqlDataSource1" and also setting the Repeater1.DataSource = objPds;. Set one or the other.
In your case you probably want to remove the DataSourceID="SqlDataSource1"
I have radio buttons which I need to keep selected between pages. I have looked up all solutions but I am still confused on what I should do.
I will supply the code which shows you the functions of the radio buttons
.aspx page
<p>What Is Your Budget?
<asp:RadioButton ID="High_B" GroupName="Budget" runat="server" Text="High"
oncheckedchanged="High_B_CheckedChanged" ViewStateMode="Enabled"
AutoPostBack="True">
</asp:RadioButton>
<asp:RadioButton ID="Low_B" GroupName="Budget" runat="server" Text="Low"
oncheckedchanged="Low_B_CheckedChanged" AutoPostBack="True"
ViewStateMode="Enabled">
</asp:RadioButton>
</p>
<p>What is the level of excitement around FWC 2014?
<asp:RadioButton ID="High_E" GroupName="Radio" runat="server" Text="High"
oncheckedchanged="High__E_CheckedChanged" ViewStateMode="Enabled"
AutoPostBack="True">
</asp:RadioButton>
<asp:RadioButton ID="Low_E" GroupName="Radio" runat="server" Text="Low"
oncheckedchanged="Low_E_CheckedChanged" AutoPostBack="True"
ViewStateMode="Enabled">
</asp:RadioButton></p>
.aspx.cs page
public void Chart()
{
if (High_E.Checked && High_B.Checked)
{
DataSet dSet = new DataSet();
dSet.ReadXml(Server.MapPath("~/ChartData/HighBud_Ex.xml"));
Chart1.DataSource = dSet.Tables[0];
Chart1.DataBind();
Session["name"] = "High";
setName();
}
if (High_E.Checked && Low_B.Checked)
{
DataSet dSet = new DataSet();
dSet.ReadXml(Server.MapPath("~/ChartData/LowBud_HighEx.xml"));
Chart1.DataSource = dSet.Tables[0];
Chart1.DataBind();
Session["name"] = "LowHigh";
setName();
}
if (Low_E.Checked && High_B.Checked)
{
DataSet dSet = new DataSet();
dSet.ReadXml(Server.MapPath("~/ChartData/HighBud_LowEx.xml"));
Chart1.DataSource = dSet.Tables[0];
Chart1.DataBind();
Session["name"] = "HighLow";
setName();
}
if (Low_E.Checked && Low_B.Checked)
{
DataSet dSet = new DataSet();
dSet.ReadXml(Server.MapPath("~/ChartData/LowBud_Ex.xml"));
Chart1.DataSource = dSet.Tables[0];
Chart1.DataBind();
Session["name"] = "Low";
setName();
}
You should preserve the state of your radioButtons between postbacks. That is, in oncheckedchanged event, save the state of your radiobutton in a Session for example, and after postback, set back those states.
i too had this problem,i used session variable to store the state of radio buttons,what i did is at postback.I stored the state of radio buttons in a string seprated by comma and then when i needed to restore the state .i used the string split function to take the values in array n dependind on the string i restored the state of the controls