Both DataSource and DataSourceID are defined on 'Repeater1' - c#

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"

Related

Split a Gridview in two Grids in c#.net

I have a GridView which gets the data from a SQL Server database.
The GridView binds when the user select the date from an CalendarExtender, because the data is different one day to another, also the rows quantity.
E. G., in Saturdays the GridView is filled with 18 rows. In Tuesdays, with 58.
Concern:
What I need to do is to split the GridView in 2 parts (2 GridViews). E. G., In tuesdays, 29 rows each GridView, in saturdays, 9 rows each.
I have tried:
To bring the daily data into a GridView, called "GVTotal":
if (Weekday.Value == "Saturday")
{
GVTotal.DataSourceID = SaturdayData.ID;
GVTotal.DataBind();
}
To count the rows from GVTotal, and divide by 2.
int everything = GVTotal.Rows.Count;
int half = everything / 2;
What I want to do now, is to "Copy" the rows from 0 to half to GVPart1, and from half to everything to GVPart2, in the exactly same order than in GVTotal.
I have read that maybe using a DataTable will made this possible.
I am not pretty sure how to do that. Could someone help me please?
You could have a Repeater with two items, one for each GridView. In the example below, the Repeater is rendered as a table with a single row. Each GridView is in a cell of that row, with an empty cell between them.
<asp:Repeater ID="repeater1" runat="server" OnItemDataBound="repeater1_ItemDataBound">
<HeaderTemplate>
<table cellspacing="0" cellpadding="0">
<tr>
</HeaderTemplate>
<ItemTemplate>
<td>
<asp:GridView ID="gvHalf" runat="server" >
...
</asp:GridView>
</td>
</ItemTemplate>
<SeparatorTemplate>
<td style="width: 32px;" />
</SeparatorTemplate>
<FooterTemplate>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
In order to get the two data sources, you declare two DataTables in your class:
private DataTable dtTopHalf;
private DataTable dtBottomHalf;
In Page_Load, the two DataTables are populated by splitting the full DataTable in two parts, and the data source of the Repeater is set to two boolean values:
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection("Data Source=(local); Integrated Security = True; Initial Catalog=TestMP"))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Clients ORDER BY ClientID ASC", conn))
{
cmd.CommandType = CommandType.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
int halfCount = dt.Rows.Count / 2;
dtTopHalf = dt.AsEnumerable().Select(x => x).Take(halfCount).CopyToDataTable();
dtBottomHalf = dt.AsEnumerable().Select(x => x).Skip(halfCount).CopyToDataTable();
}
// Each value in the Repeater indicates if it is the top half or not
repeater1.DataSource = new List<bool>() { true, false };
repeater1.DataBind();
}
}
The specific data source can then be set for each GridView in the ItemDataBound event handler of the Repeater:
protected void repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
bool isTopHalf = (bool)e.Item.DataItem;
GridView gvHalf = e.Item.FindControl("gvHalf") as GridView;
gvHalf.DataSource = isTopHalf ? dtTopHalf : dtBottomHalf;
gvHalf.DataBind();
}
}
Note 1: The Repeater allows to share the same markup for both GridViews. If you prefer, you can declare two separate GridViews in the markup and apply the specific data source to each one in Page_Load.
Note 2: You need a reference to System.Data.DataSetExtensions in your project to use some of the LINQ methods mentioned above.
Thanks to ConnorsFan for the assistance. His answer is the right way to do what I wanted.
As I need to select the date before the data comes in, I wrote Connor's code into my date Textbox OnTextChanged event, into the if (Weekday.Value == "<day of the week>") statement.
This is the solution:
ASPX:
Updated: Only with one GridView, as reccomended:
<asp:Repeater ID="repeater1" runat="server" OnItemDataBound="repeater1_ItemDataBound">
<HeaderTemplate>
<table cellspacing="200px" cellpadding="0">
<tr style="vertical-align: top;">
</HeaderTemplate>
<ItemTemplate>
<td>
<asp:GridView ID="gvHalf" runat="server" BackColor="White" AutoGenerateColumns="False" HeaderStyle-CssClass="tituloshandoff" RowStyle-CssClass="contenidohandoffbatch">
<Columns>
<asp:BoundField HeaderText="IDBATCH" DataField="IDBatch" SortExpression="IDBatch" HeaderStyle-CssClass="TituloInvisible" ItemStyle-CssClass="TituloInvisible" />
<asp:BoundField HeaderText="BATCH" DataField="Nombre" SortExpression="Nombre" />
<asp:BoundField HeaderText="DEALER" DataField="DealerCodigo" SortExpression="DealerCodigo" />
<asp:BoundField HeaderText="CT TIME" DataField="CTStart" SortExpression="CTStart" />
<asp:BoundField HeaderText="STATUS" DataField="Estado" SortExpression="Estado" />
<asp:TemplateField HeaderText="CONTROL">
<ItemTemplate>
<asp:Button ID="Button1" CssClass="botongrid" runat="server" Text="Select" Width="100px" /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</ItemTemplate>
<SeparatorTemplate>
<td style="width: 100px;" />
</SeparatorTemplate>
<FooterTemplate>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
C#:
I will show only one day in example:
string LaConexion = #"<My Connection String>";
private DataTable dtTopHalf;
private DataTable dtBottomHalf;
protected void TextDate_TextChanged(object sender, EventArgs e)
{
if (diasemana.Value == "Monday")
{
using (SqlConnection conexion = new SqlConnection(LaConexion))
using (SqlCommand comando = new SqlCommand("SELECT [1Monday].IDBatch, Batch.Nombre, Dealer.DealerCodigo, Batch.CTStart, BatchDatos.Estado FROM [1Monday] INNER JOIN Batch ON [1Monday].IDBatch = Batch.IDBatch INNER JOIN Dealer ON Batch.IDDealer = Dealer.IDDealer LEFT OUTER JOIN BatchDatos ON [1Monday].ID = BatchDatos.ID ORDER BY Batch.CTStart", conexion))
{
comando.CommandType = CommandType.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(comando);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
int halfCount = dt.Rows.Count / 2;
dtTopHalf = dt.AsEnumerable().Select(x => x).Take(halfCount).CopyToDataTable();
dtBottomHalf = dt.AsEnumerable().Select(x => x).Skip(halfCount).CopyToDataTable();
}
// Each value in the Repeater indicates if it is the top half or not
repeater1.DataSource = new List<bool>() { true, false };
repeater1.DataBind();
}
}
A Picture:

Loop through all check boxes in Table

I have a table cell that I fill with CheckBoxes and Labels at runtime.
List<string> lstUserPool = new List<string>();
DataTable dt = GetData("SELECT UserName FROM eData ORDER BY UserName;", "Data Source = lewcomp1\\COMPLIANCE; Initial Catalog = ComplianceData; Integrated Security = True;");
for (int i = 1; i < dt.Rows.Count; i++)
{
CheckBox cb = new CheckBox();
cb.ID = "cb" + dt.Rows[i]["Username"].ToString();
Label lbl = new Label();
lbl.ID = "lbl" + dt.Rows[i]["Username"].ToString();
lbl.Text = dt.Rows[i]["Username"].ToString();
lbl.Font.Size = new FontUnit("18px");
if (IsOdd(i))
{
cellUsersPoolLeft.Controls.Add(cb);
cellUsersPoolLeft.Controls.Add(lbl);
cellUsersPoolLeft.Controls.Add(new LiteralControl("<br/>"));
}
if (IsEven(i))
{
cellUsersPoolRight.Controls.Add(cb);
cellUsersPoolRight.Controls.Add(lbl);
cellUsersPoolRight.Controls.Add(new LiteralControl("<br/>"));
}
}
Later, I'd like to loop through these Checkboxes to check what is Checked and what is not. I've tried various examples found on SO but with no luck. It's almost as if the checkboxes are not in the TableCell that I'v added them to. Both of the below loops do not find any checkbox controls:
foreach (Control ctl in cellUsersPoolRight.Controls)
{
if (ctl is CheckBox)
{
}
}
//foreach(var checkBox in cellUsersPoolRight.Controls.OfType<CheckBox>())
//{
// if (checkBox.Checked)
// {
// naz.Add(checkBox.ID);
// }
//}
I suggest you use a Repeater and Databind a Checkbox and Label to ItemTemplate in the repeater. This will easily allow you to get the data by looping through the repeater. If you need additional data add Hiddenfield within the repeater to store them.
<asp:Repeater ID="UserRepeater" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:CheckBox ID="UserCheckBox" runat="server" Checked='<%# Convert.ToBoolean(Eval("IsUserChecked")) %>' ToolTip='<%# Eval("UserId") %>'
onmouseover="title='';" />
</td>
<td>
<asp:Label ID="UserNameLabel" runat="server" Text='<%# Eval("UserName") %>'></asp:Label>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Then in your codebehind
//initialize repeater data
userRepeater.DataSource = dt;
userRepeater.DataBind();
Then in postback of your imagebutton_click you can get the items from the repeater
foreach (RepeaterItem ri in UserRepeater.Items)
{
CheckBox userCheckBox = ri.FindControl("UserCheckBox") as CheckBox;
}
Sorry, I cannot write in comments yet.
On which event are you trying to add the control and on which are you trying to read from it?
Take a look at this post to read more.
check the order of events on page, and if you are using the correct event in the life cycle.

ASP.NET Dropdownlist causing issue

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.

Getting value from textarea in ASP.NET repeater?

I have an asp.net repeater control, displaying data from a sql db.
I have delete, edit and save buttons displaying next to each record, sort of like an admin.
When edit is clicked, hidden textboxes appear in place of the literals that were displaying the data.
When save is clicked, the new values should be saved to the db (which they are), and the literals display the new value.
But the new value strings are returning as empty strings. They're not null, but the string contains no characters!
This worked fine when I had two TextBox's , however when I switched one to a HTMLTextArea , this happened!
Here is my relevant code...
if (e.CommandName == "edit")
{
((TextBox)e.Item.FindControl("Onebox")).Visible = true;
((TextBox)e.Item.FindControl("Onebox")).Text = ((Literal)e.Item.FindControl("onelit")).Text;
((HtmlTextArea)e.Item.FindControl("Threebox")).Visible = true;
((HtmlTextArea)e.Item.FindControl("Threebox")).Value = ((Literal)e.Item.FindControl("threelit")).Text;
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
((Literal)e.Item.FindControl("onelit")).Visible = false;
((Literal)e.Item.FindControl("threelit")).Visible = false;
((LinkButton)e.Item.FindControl("LinkButton2")).Visible = false;
((LinkButton)e.Item.FindControl("LinkButton3")).Visible = true;
}
if (e.CommandName == "save")
{
string newoneval = ((TextBox)e.Item.FindControl("Onebox")).Text;
string newtwoval = ((HtmlTextArea)e.Item.FindControl("Threebox")).Value;
((TextBox)e.Item.FindControl("Onebox")).Visible = false;
((Literal)e.Item.FindControl("onelit")).Text = ((TextBox)e.Item.FindControl("Onebox")).Text;
((HtmlTextArea)e.Item.FindControl("Threebox")).Visible = false;
((Literal)e.Item.FindControl("threelit")).Text = ((HtmlTextArea)e.Item.FindControl("Threebox")).Value;
((Literal)e.Item.FindControl("onelit")).Visible = true;
((Literal)e.Item.FindControl("threelit")).Visible = true;
((LinkButton)e.Item.FindControl("LinkButton2")).Visible = true;
((LinkButton)e.Item.FindControl("LinkButton3")).Visible = false;
if(newoneval != null && newtwoval != null)
{
SqlDataReader dataReader;
String editstr = "update news set title = '" + newoneval + "', short_desc ='" + newtwoval + "' where pk_ID = #pk_ID";
SqlCommand command = new SqlCommand(editstr, conn);
command.Parameters.AddWithValue("#pk_ID", e.CommandArgument);
try
{
conn.Open();
dataReader = command.ExecuteReader();
dataReader.Close();
command.Dispose();
conn.Close();
BindRepeater();
}
catch (Exception exc)
{
Response.Write(exc);
}
}
else
{
Response.Write("No value");
}
and here is the asp repeater template...
<asp:Repeater ID="list_holder" runat="server" OnItemCommand="runCommands">
<ItemTemplate>
<table>
<tr>
<!-- FIRST BOX CONTROLS ---------------->
<td class="cells">
<asp:Textbox id="Onebox"
text=''
runat="server"
enabled="true"
visible="false">
</asp:Textbox>
<asp:Literal id="onelit"
runat="server"
text='<%# DataBinder.Eval(Container.DataItem ,"title") %>'
/>
</td>
<td class="cells">
<textarea id="Threebox"
text=''
runat="server"
enabled="true"
Visible="false">
</textarea>
<asp:Literal id="threelit"
text='<%# DataBinder.Eval(Container.DataItem ,"short_desc") %>'
runat="server"
/>
</td>
<!-------------------------------------->
<!---- Link Buttons ------------------------>
<td class="cells">
<asp:LinkButton ID="LinkButton1"
runat="server"
CommandName="delete"
OnClientClick='javascript:return confirm("Are you sure you want to delete?")'
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "pk_ID") %>'
CausesValidation="false">Delete</asp:LinkButton>
</td>
<td class="cells">
<asp:LinkButton ID="LinkButton2"
runat="server"
CommandName="edit"
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "pk_ID") %>'
CausesValidation="false"
Visible ="true">Edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton3"
runat="server"
CommandName="save"
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "pk_ID") %>'
CausesValidation="false"
Visible ="false">Save</asp:LinkButton>
</td>
<!-------------------------------------------------->
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Why are both the strings returning empty, when before they were returning correctly?
In ASP.NET when you set visible to false, Control don't render on page.
For more see MSDN.

Textboxes Causing Problems in ASP.NET C# SQL

I am using a nested Gridview(I have 5 Nested Gridviews).
I have applied a Regular Field validator for these Gridviews.
But once I click the button, commas are generated in the textbox. Due to that whenever I click the button, all the validation get fired.
I have researched lots of articles but have not found one related to this.
Here is the image for the Gridview with the commas generated in the textbox:
HTML Code Part
<%-- First Gridview--%>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
CssClass="gvstyling gridview_width_60" ShowHeaderWhenEmpty="true" EmptyDataText="Record(s) Not Found!"
DataKeyNames="locality" ShowHeader="false" OnRowDataBound="gvLocality_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlCompanyName" runat="server" Style="display: none">
<%-- Second Gridview --%>
<asp:GridView ID="gvCompanyName" ShowHeader="false" ShowHeaderWhenEmpty="false" CssClass="gvstyling gridview_width_100"
OnRowDataBound="gvCompanyName_RowDataBound" runat="server"
AutoGenerateColumns="false" EmptyDataText="No Record(s) Found!">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<asp:HiddenField ID="hfRetailer_Id" Value='<%# Eval("retailer_id") %>' runat="server"></asp:HiddenField>
<asp:HiddenField ID="hfLocality" Value='<%# Eval("locality") %>' runat="server"></asp:HiddenField>
<asp:Label ID="lbl" Visible="false" Text='<%# Eval("retailer_id") %>' runat="server"></asp:Label>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlSellOrderNo" runat="server" Style="display: none">
<%-- Third Gridview --%>
<asp:GridView ID="gvSellOrderNo" ShowHeader="false" ShowHeaderWhenEmpty="false"
CssClass="gvstyling gridview_width_100" runat="server" OnRowDataBound="gvSellOrderNo_RowDataBound"
AutoGenerateColumns="false" EmptyDataText="No Record(s) Found!">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<asp:HiddenField ID="hf_SellOrderNo" Value='<%# Eval("sell_order_no") %>' runat="server"></asp:HiddenField>
<asp:Label ID="lblSellOrderNo" Visible="false" Text='<%# Eval("sell_order_no") %>' runat="server"></asp:Label>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlProductDetails" runat="server" Style="display: none">
<%-- fourth Gridview --%>
<asp:GridView ID="gvProductDetails" ShowHeader="false" ShowHeaderWhenEmpty="false"
CssClass="gvstyling gridview_width_100" runat="server" OnRowDataBound="gvProductDetails_RowDataBound"
AutoGenerateColumns="false" EmptyDataText="No Record(s) Found!">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" Value='<%# Eval("sell_order_no") %>' runat="server"></asp:HiddenField>
<asp:HiddenField ID="hfProductId" Value='<%# Eval("product_id") %>' runat="server"></asp:HiddenField>
<asp:Label ID="lblProductId" Visible="false" Text='<%# Eval("product_id") %>' runat="server"></asp:Label>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlWarehouseDetails" runat="server" Style="display: none">
<%-- fifth Gridview--%>
<asp:GridView ID="gvWarehouseDetails" ShowHeader="false" ShowHeaderWhenEmpty="false"
CssClass="gvstyling gridview_width_100" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblWarehouseId" Text='<%# Eval("c_warehouse_id") %>' Visible="false" runat="server"></asp:Label>
<%# Eval("warehouse_name") %> (<%# Eval("qty") %>)
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- fifth Gridview --%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("product_name") %> (<%# Eval("qty") %>)
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- fourth Gridview --%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("sell_order_no") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- Third Gridview --%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Business Name">
<ItemTemplate>
<%# Eval("business_name") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- Second Gridview--%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="gv_item_bg">
<ItemTemplate>
<asp:Label ID="lblLocality" runat="server" Text=' <%# Eval("locality") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- First Gridview --%>
Code Behind File
//Filling Shipping Company Name
private void FillShippingCompanyName()
{
try
{
ArrayList arr = new ArrayList();
cm.ds.Clear();
cm.sp_dataset_execute("spdisplay_Shipping_Comany_Name", arr);
ddlCompanyName.DataSource = cm.ds;
ddlCompanyName.DataValueField = "shipping_code";
ddlCompanyName.DataTextField = "shipping_name";
ddlCompanyName.DataBind();
ddlCompanyName.Items.Insert(0, new ListItem("---- Select Shipping Company ----", "0"));
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-FillShippingCompanyName()");
}
finally
{
cm.con.Close();
}
}
private void FillLocality()
{
try
{
cm.ds.Clear();
ArrayList arr = new ArrayList();
cm.sp_dataset_execute("spDisplay_Locality", arr);
gvLocality.DataSource = cm.ds;
gvLocality.DataBind();
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-FillLocality()");
cm.con.Close();
}
finally
{
cm.con.Close();
}
}
//Locality Gridview Row Databound (Level 1 Grdview)
common cm1 = new common();
protected void gvLocality_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Locality = gvLocality.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvCompanyName = e.Row.FindControl("gvCompanyName") as GridView;
cm1.ds.Clear();
//Binding Company Gridview
ArrayList arr1 = new ArrayList();
arr1.Add("#locality|" + Locality + "");
cm1.sp_dataset_execute("spDisplayCompanyName", arr1);
gvCompanyName.DataSource = cm1.ds;
gvCompanyName.DataBind();
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Recent_activity-gvRecentActivityOuter_RowDataBound()");
cm1.con.Close();
}
finally
{
cm1.con.Close();
}
}
//Comapny Name Gridview Row Databound (Level 2 Grdview)
common cm2 = new common();
protected void gvCompanyName_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string RetailerId = ((HiddenField)e.Row.FindControl("hfRetailer_Id")).Value;
GridView gvSellOrderNo = e.Row.FindControl("gvSellOrderNo") as GridView;
string Locality = ((HiddenField)e.Row.FindControl("hfLocality")).Value;
cm2.ds.Clear();
//Binding Company Gridview
ArrayList arr = new ArrayList();
arr.Add("#retailer_id|" + RetailerId + "");
arr.Add("#locality|" + Locality + "");
cm2.sp_dataset_execute("spDisplay_SellOrderNo", arr);
gvSellOrderNo.DataSource = cm2.ds;
gvSellOrderNo.DataBind();
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-Page_Load()");
cm2.con.Close();
}
finally
{
cm2.con.Close();
}
}
//Sell Order Gridview Row Databound (Level 3 Grdview)
common cm3 = new common();
protected void gvSellOrderNo_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string SellOrderNo = ((HiddenField)e.Row.FindControl("hf_SellOrderNo")).Value;
GridView gvProductDetails = e.Row.FindControl("gvProductDetails") as GridView;
FillProductDetails(gvProductDetails, SellOrderNo);
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-gvSellOrderNo_RowDataBound()");
cm3.con.Close();
}
finally
{
cm3.con.Close();
}
}
private void FillProductDetails(GridView gvProductDetails, string SellOrderNo)
{
cm3.ds.Clear();
//Product Details Gridview
ArrayList arr = new ArrayList();
arr.Add("#sell_order_no|" + SellOrderNo + "");
cm3.sp_dataset_execute("spDisplay_ProductDetails", arr);
gvProductDetails.DataSource = cm3.ds;
gvProductDetails.DataBind();
}
//Product Details Gridview Row Databound (Level 4 Grdview)
common cm4 = new common();
protected void gvProductDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ProductID = ((HiddenField)e.Row.FindControl("hfProductId")).Value;
string SellOrderNo = ((HiddenField)e.Row.FindControl("HiddenField1")).Value;
GridView gvWarehouseDetails = e.Row.FindControl("gvWarehouseDetails") as GridView;
cm4.ds.Clear();
//Product Details Gridview
ArrayList arr = new ArrayList();
arr.Add("#product_id|" + ProductID + "");
arr.Add("#sell_order_no|" + SellOrderNo + "");
cm4.sp_dataset_execute("spDisplay_WarehouseDetails", arr);
gvWarehouseDetails.DataSource = cm4.ds;
gvWarehouseDetails.DataBind();
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-gvProductDetails_RowDataBound()");
cm4.con.Close();
}
finally
{
cm4.con.Close();
}
}
//Submit Button
protected void btnSubmit_Click1(object sender, EventArgs e)
{
try
{
cm.ds.Clear();
//--Insert Query for Rs_Shipping_Order_Details
string ShippingCode = "SHO" + DateTime.Now.ToString("yyyyMMddHHmmss");
string ShippingGroup = "SG" + DateTime.Now.ToString("yyyyMMddHHmmss");
ArrayList arr = new ArrayList();
arr.Add("#shipping_code|" + ShippingCode + "");
arr.Add("#shipping_Company_code|" + ddlCompanyName.SelectedValue + "");
arr.Add("#is_shipping_delivered|0");
cm.sp_execute("spInsert_Shipping_Order_Detail", arr);
//Locality for loop
for (int i = 0; i < gvLocality.Rows.Count; i++)
{
GridView gvCompanyName = gvLocality.Rows[i].FindControl("gvCompanyName") as GridView;
//Company for loop
for (int j = 0; j < gvCompanyName.Rows.Count; j++)
{
GridView gvSellOrderNo = gvCompanyName.Rows[j].FindControl("gvSellOrderNo") as GridView;
string RetailerId = ((Label)gvCompanyName.Rows[j].FindControl("lbl")).Text;
//Sell Order for loop
for (int k = 0; k < gvSellOrderNo.Rows.Count; k++)
{
//Product Details Gridview
GridView gvProductDetails = gvSellOrderNo.Rows[k].FindControl("gvProductDetails") as GridView;
string SO = ((Label)gvSellOrderNo.Rows[k].FindControl("lblSellOrderNo")).Text;
int retailer_Id = Convert.ToInt32(RetailerId);
//Product Details for loop
for (int l = 0; l < gvProductDetails.Rows.Count; l++)
{
//Warehouse Details Gridview
GridView gvWarehouseDetails = gvProductDetails.Rows[l].FindControl("gvWarehouseDetails") as GridView;
string ProductId = ((Label)gvProductDetails.Rows[l].FindControl("lblProductId")).Text;
//Warehouse Details for loop
for (int m = 0; m < gvWarehouseDetails.Rows.Count; m++)
{
TextBox txtQty = gvWarehouseDetails.Rows[m].FindControl("txtQty") as TextBox;
string LastValue = txtQty.Text.Split(',').Last();
if (String.IsNullOrEmpty(LastValue) == false)
{
string Warehouse_Id = ((Label)gvWarehouseDetails.Rows[m].FindControl("lblWarehouseId")).Text;
int warehouse_id = Convert.ToInt32(Warehouse_Id);
string Qty = LastValue;
//Insert Query for Rs_Shipping_Detail_Mapping
ArrayList arr1 = new ArrayList();
arr1.Add("#shipping_order_code|" + ShippingCode + "");
arr1.Add("#retailer_id|" + retailer_Id + "");
arr1.Add("#sell_order_no|" + SO + "");
arr1.Add("#product_id|" + ProductId + "");
arr1.Add("#c_warehouse_id|" + warehouse_id + "");
arr1.Add("#shipping_group|" + ShippingGroup + "");
arr1.Add("#qty|" + Qty + "");
common cm1 = new common();
cm1.sp_execute("spInsert_Shipping_Detail_Mapping", arr1);
////Generating Pdf for Each Sell Order
//if (m == gvWarehouseDetails.Rows.Count - 1)
//{
// Generate_SellOrderWise_PDf(SO, ShippingCode, ShippingGroup);
//}
}
}
}
}
}
}
Response.Redirect("../final-shipping-order/?SG=" + ShippingGroup, false);
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-btnSubmit_Click1()");
cm4.con.Close();
}
finally
{
cm4.con.Close();
}
}
Question :
1. How do I remove the commas from the textboxes?
2. Reason for these commas? (Why are the commas being generated on the button click?)
3. Limit for the Nested Gridview ?
Any help will be appreciated.
When you have duplicate form field names, the values are concatenated together with commas.
So, for example, if you have the following..
<input type="text" name="name" value="">
<input type="text" name="name" value="">
.. your resulting value on Request.Form postback looks like this:
name=,,
That's what's happening.
Here are a few possible solutions to your problem, though I have not tested any of them :)
1) UpdatePanel
From reading, it seems that if you create an UpdatePanel for the offending grid control (<asp:TextBox ID="txtQty" runat="server"></asp:TextBox>) , it removes this problem. Again, I have not tested this
2) Changing DataBind() behavior during Page_Load()
So...
page_load()
{
if(!isPostBack())
{
// DataBind normally
myGridview.DataBind();
}
else
{
//Some intelligent way to remove commas before binding
}
}
... But that doesn't change the fact that the ,,,values are being posted in the first place. And so, if your primarily concerned with the end aesthetic and not behavior, you can just use JS to strip out the commas (as previously suggested hinted at.)
3) JS - Get Rid of the Commas:
(as suggested here)
<script type="text/javascript">
$("[src*=plus]").live("click", function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
$("input", $(this).closest("tr").next()).each(function () {
this.value = this.value.substring(',', '');
});
});
$("[src*=minus]").live("click", function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
});
</script>
Hope this helps :)
[Edit] - Validation
I would fire off validation using the .keydown() event. In your case, it might look something like this:
// Bind to each input with id='txtQty', in each row, in the "gridview" with id='gvWarehouseDetails'
$("#gvWarehouseDetails tr input[id*='txtQty']").each(function () {
$(this).keydown(function (event) { // <-- specifies the specific input
// Validation logic goes here...
});
});
The Ajax Control Toolkit is a viable solution, however support for it has become non-existent. I'm assuming there is a level of dynamic control on that field. In essence, the grid will display it at certain instances?
Either way, you could add a specific class to the field:
<asp:Textbox id="txtContent" runat="server" CssClass="Validator">
Essentially when the grid adds all of these fields to your page, they'll all have the Validator class. So you can write JavaScript to actually strip the character out of the field, example:
$('.Validator').on('blur', function() {
$(this).replace(',', '');
});
As soon as the focus changes, that field will remove the , from the field as soon as the mouse leaves the , will be removed from the field.
That is one approach, countless other options do exist as well to accomplish this. This solution is pretty easy, agile, and light so it should be adequate.
Update:
The solution I chose shouldn't require a loop over those fields. Simply because blur triggers whenever a change or focus is lost on that field. Since you mentioned the , appears when the user clicks in the field. Otherwise you could do validation on all the fields. All you simply would need to do:
$('.Validator').each(function() {
// Will iterate through each field.
});
So you could essentially use JavaScript yourself to validate those fields, or use a simple library such as Valid8 which will do all client-side validation. No postback, all done client side before sent to the server to process.
Avoid:
Update Panel - These are quite a pain and incredibly inefficient. The way they work basically is by taking your entire page and storing it memory then does an Ajax request and refreshes your page and pulls all the contents out of memory to place on the page. Additionally it makes working with the Asp.Net Page Life Cycle incredibly difficult.
Hardik, how is txtQty.Text bound at first?
Does it come as an empty text box?
You using the code string LastValue = txtQty.Text.Split(',').Last(); to try go get rid of this comma values inserted or the values bound come with commas? I mean, you using the same UI culture from values in the database and the app or do you have to format it before displaying it?
I Don't know what is happening in your code. But If you want to get rid of Comma (',') then I should suggest one thing to you.
Add a reference of AjaxControlToolKit and register it in your aspx page as shown below:
<%# Register TagPrefix="ajaxToolkit" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit, Version=[VersionNumber], Culture=neutral, PublicKeyToken=[TokenNumber]" %>
Or You can refer How to install AJAX Control toolkit
Once you have installed AJAX Control Toolkit, Go to your page and in your grid TemplateField, below TextBox txtQty, add FilteredTextBoxExtender as shown below:
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender runat="server" InvalidChars="," FilterMode="InvalidChars" TargetControlID="txtQty" />
</ItemTemplate>
</asp:TemplateField>
By Adding FilterTextBoxExtender, It will not allow characters to be inserted which are mentioned as InvalidChars to the textbox 'txtQty'.

Categories