Client:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table id="Table_car">
<tr>
<th>Pos#</th>
<th>Model</th>
<th>Price</th>
<th>Image</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("Pos#") %></td>
<td><%# Eval("Model") %></td>
<td><%# Eval("Price") %></td>
<td><%# Eval("Image ") %></td>
</tr>
</ItemTemplate>
Server:
protected void Page_Load(object sender, EventArgs e) {
var table = new DataTable();
try
{
using (var conn = new SqlConnection(_connectionString))
{
using (var cmd = new SqlCommand("spFilterByContinent", conn))
{
using (var adapter = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.StoredProcedure;
adapter.Fill(table);
}
}
}
Repeater1.DataSource = table;
Repeater1.DataBind();
}
catch (Exception exception)
{
//TODO: write excepetion
}
}
public void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
string header1 = string.Empty;
string header2 = string.Empty;
string header3 = string.Empty;
string header4 = string.Empty;
// Retrieve headers from database and assign to variables
SetHeaderValue(e.Item, "litHeader1", header1);
SetHeaderValue(e.Item, "litHeader2", header2);
SetHeaderValue(e.Item, "litHeader3", header3);
SetHeaderValue(e.Item, "litHeader4", header4);
}
}
private void SetHeaderValue(RepeaterItem item, string litId, string headerText)
{
var lit = item.FindControl(litId) as Literal;
if (lit != null)
lit.Text = headerText;
}
}
I am using a repeater for retrieving data from db,
my question is: How can I retrieve columns headers from db also, not just the data itself?
<# Eval("COLUMN HEADER")%> <---alike
Headers are not databound as the items of a repeater (see this question and its answers for details). But you can adjust the headers in the ItemCreated event of the Repeater. First, you'd need to place some literal controls in the headers and add a handler for the ItemCreated event:
<asp:Repeater ID="Repeater1" runat="server" OnItemCreated="Repeater1_ItemCreated">
<HeaderTemplate>
<table id="Table_car">
<tr>
<th><asp:Literal ID="litHeader1" runat="server" /></th>
<th><asp:Literal ID="litHeader2" runat="server" /></th>
<th><asp:Literal ID="litHeader3" runat="server" /></th>
<th><asp:Literal ID="litHeader4" runat="server" /></th>
</tr>
</HeaderTemplate>
</HeaderTemplate>
<!-- ... -->
</asp:Repeater>
Then you'd need to implement the event handler in the code behind file. Based on your question, this sample assumes that you want to use the column names of the data table that is assigned as the DataSource of the Repeater:
protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
var tbl = (DataTable)((Repeater)sender).DataSource;
SetHeaderValue(e.Item, "litHeader1", tbl, 0);
SetHeaderValue(e.Item, "litHeader2", tbl, 1);
SetHeaderValue(e.Item, "litHeader3", tbl, 2);
SetHeaderValue(e.Item, "litHeader4", tbl, 3);
}
}
private void SetHeaderValue(RepeaterItem item, string litId, DataTable tbl, int colIndex)
{
var lit = item.FindControl(litId) as Literal;
if (lit != null)
{
string headerText =
tbl.Columns.Count > colIndex ? tbl.Columns[colIndex].ColumnName : "Not set";
lit.Text = headerText;
}
}
Related
I am appending rows using item template
<tr>
<td>
<asp:HyperLink ID="HyperLink1" NavigateUrl="bla" CssClass="display:inherit !important;" Text='<%# someFunction(School.Name,"Name") %>' runat="server" />
</td>
</tr>
the problem with the above one is if someFunction(School.Name,"Name") returns null it appends empty tr, so i want to append tr only if someFunction(School.Name,"Name")!=null
So i tried the below code by adding a if condition but it is not compiling !!
It says school.name is not defined
<% if(someFunction(School.Name,"Name")!=null){
<tr>
<td>
<asp:HyperLink ID="HyperLink1" NavigateUrl="bla" CssClass="display:inherit !important;" Text='<%# someFunction(School.Name,"Name") %>' runat="server" />
</td>
</tr>
} %>
You could take care of it from the code behind.
<td id="tdAppend" runat="server"> Content </td>
if(School.Name == null)
tdAppend.Visible = false;
UPDATED ANSWER:
currentItemIndex = -1;
listView.ItemDataBound += listView_ItemDataBound;
CheckQueryString();
//Hide or show the table header based on id
HtmlControl thControl = listView.FindControl("thAppend") as HtmlControl;
if (thControl != null)
{
if (obj.ID == 12)
{
thControl.Visible = true;
}
else
{
thControl.Visible = false;
for (int i = 0; i < listView.Items.Count; i++)
{
HtmlControl tdControl = listView.Items[i].FindControl("tdSchoolName") as HtmlControl;
if (tdControl != null)
{
tdControl.Visible = false;
}
}
}
}
For convenience:
void listView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
currentItemIndex++;
ListViewDataItem dataitem = (ListViewDataItem)e.Item;
HtmlTableRow trControl = (HtmlTableRow)e.Item.FindControl("MainTableRow");
if (IsOdd(currentItemIndex))
trControl.BgColor = "DarkGray";
}
}
private bool IsOdd(int value)
{
return value % 2 != 0;
}
It's a pretty straight forward practice.. Handling the ListView.OnItemDataBinding event.
Markup
<%# Import Namespace="MyNamespace" %>
<asp:ListView ID="lview" runat="server" OnItemDataBound="lview_ItemDataBound" ItemPlaceholderID="Placeholder1">
<ItemTemplate>
<tr>
<td><%# ((School)Container.DataItem).Name %></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table>
<div id="Placeholder1" runat="server"></div>
</table>
</LayoutTemplate>
</asp:ListView>
Code-Behind
namespace MyNamespace
{
public class Default : Page
{
IEnumerable<School> dataItems {get;set;}
protected void Page_Load(object sender, EventArgs e)
{
dataItems = new School[] { new School() { Name = "School 1" }, new School() { Name = "School 2" }, new School() { Name = null }, new School() { Name = "School 3" } }.AsEnumerable();
lview.DataSource = dataItems;
lview.DataBind();
}
protected void lview_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListView listview = (ListView)sender;
ListViewItem row = e.Item;
School dataItem = (School)e.Item.DataItem;
if (dataItem.Name == null)
{
row.Visible = false;
}
}
}
public class School
{
public string Name { get; set; }
}
}
personally, I don't usually use tables.. it's a fairly odd-looking layout template.
I have a 2 Dropdownlist outside a repeater (1st ddl will trigger and refresh the content of the repeater, 2nd ddl refresh its list after an item inside the repeater were executed) and a dropdownlist control inside the repeater.i don't have a problem with the 1st dropdownlist but the 2nd dropdownlist when triggered via selectedindexchanged, it also fires up the selectedindexchanged of the dropdownlist inside the repeater. I put up an UpdatePanel on the repeater and on the 2nd dropdownlist but still the error occurs.
How can i trace the step by step execution and also why the selectedindexchanged handler fires up?
Here is the code snippet:
CODE BEHIND:
public partial class NewStyleItem : System.Web.UI.Page
{
protected StyleTemplateManager styleTempMngr = new StyleTemplateManager();
protected StyleFabricationManager styleFabMngr = new StyleFabricationManager();
protected List<ComponentReferenceView> ReferenceLookUpList
{
get
{
return (List<ComponentReferenceView>)ViewState["ReferenceLookUpView"];
}
set
{
ViewState["ReferenceLookUpView"] = value;
}
}
protected List<ComponentReferenceView> ReferenceViewList
{
get
{
return (List<ComponentReferenceView>)ViewState["CompReferenceView"];
}
set
{
ViewState["CompReferenceView"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
LoadBrandList();
ddlGarmentList.Enabled = false;
//ReferenceLookUpList = new List<ComponentReferenceView>();
}
else
{
}
//rptStyleComponents.DataSource = ReferenceLookUpList;
//rptStyleComponents.DataBind();
}
protected void LoadBrandList()
{
BrandManager brandMngr = new BrandManager();
ddlBrandList.Items.Clear();
ddlBrandList.Items.Add(new ListItem { Text = "Select brand", Value = "" });
foreach (Brand item in brandMngr.Brands())
{
ddlBrandList.Items.Add(new ListItem
{
Text = item.BrandDescription,
Value = item.BrandCode
});
}
}
protected void LoadComponentInfo(string BrandCode)
{
if (styleTempMngr.FindTemplateByBrandCode(BrandCode) == true)
{
ReferenceLookUpList = (from StyleComponent i in styleFabMngr.ComponentList
join StyleFabReference x in styleTempMngr.ReferenceList on
i.SectionCode equals x.SectionCode
select new ComponentReferenceView
{
InOrder = x.SortOrder,
IsNeeded = x.IsRequired,
SCode = x.SeriesCode,
SecCode = x.SectionCode,
SecName = i.SectionName,
EntryValue = x.DataCharacter
}).OrderBy(p => p.InOrder).ToList();
ReferenceLookUpList.Where(row => row.SecCode == "BCODE").ToList()
.ForEach(refItem => refItem.EntryValue = ddlBrandList.SelectedValue);
var DistinctList = (from StyleFabReference x in styleTempMngr.ReferenceList.OrderBy(p => p.SortOrder).ToList()
where x.SectionCode != "SPCHAR" && x.SectionCode != "BCODE"
select x.SectionCode).Distinct().ToList();
ReferenceViewList = (from StyleComponent i in styleFabMngr.ComponentList
join x in DistinctList on
i.SectionCode equals x
select new ComponentReferenceView
{
SecCode = x,
SecName = i.SectionName
}).OrderBy(p => p.InOrder).ToList();
}
else
ReferenceViewList = new List<ComponentReferenceView>();
rptStyleComponents.DataSource = ReferenceViewList;
rptStyleComponents.DataBind();
}
protected void LoadGarments(string ApparelCode)
{
if (string.IsNullOrEmpty(ddlBrandList.SelectedValue) == true)
{
ddlGarmentList.SelectedIndex = 0;
ddlGarmentList.Enabled = false;
}
else
{
ddlGarmentList.Enabled = true;
GarmentManager gmMngr = new GarmentManager();
List<Garment> garmentList = new List<Garment>();
garmentList = gmMngr.GetGarmentsByBrand(ddlBrandList.SelectedValue, ApparelCode);
ddlGarmentList.Items.Clear();
ddlGarmentList.Items.Add(new ListItem { Text = "Select garment", Value = "" });
foreach (Garment item in garmentList)
{
ddlGarmentList.Items.Add(new ListItem { Text = item.GarmentDescription, Value = item.GarmentCode });
}
}
}
protected void ddlBrandList_SelectedIndexChanged(object sender, EventArgs e)
{
txtNewStyleNo.Text = string.Empty;
if (string.IsNullOrEmpty(ddlBrandList.SelectedValue) == false)
LoadComponentInfo(ddlBrandList.SelectedValue);
}
[Serializable]
public class ComponentReferenceView
{
public string SCode
{
get;
set;
}
public string SecCode
{
get;
set;
}
public string SecName
{
get;
set;
}
public int InOrder
{
get;
set;
}
public bool IsNeeded
{
get;
set;
}
public string EntryValue
{
get;
set;
}
}
protected void rptStyleComponents_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
}
protected void rptStyleComponents_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddlControl = (DropDownList)e.Item.FindControl("ddlDataSelection");
if (ddlControl != null)
{
ddlControl.AppendDataBoundItems = true;
ddlControl.Items.Add(new ListItem { Text = "Select " + ReferenceViewList[e.Item.ItemIndex].SecName.ToLowerInvariant(), Value = "" });
var itemlist = (from x in styleFabMngr.ComponentRowItems(ReferenceViewList[e.Item.ItemIndex].SecCode).AsEnumerable()
select new ListItem
{
Text = x.Field<string>("col_name"),
Value = x.Field<string>("col_value")
});
ddlControl.Items.AddRange(itemlist.ToArray<ListItem>());
ddlControl.EnableViewState = false;
ddlControl.AutoPostBack = true;
ddlControl.SelectedIndexChanged += new EventHandler(DropDownListSelectedIndexChanged);
}
}
}
protected virtual void DropDownListSelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
RepeaterItem item = (RepeaterItem)ddl.NamingContainer;
ReferenceViewList[item.ItemIndex].EntryValue = ddl.SelectedValue;
ConstructStyleNo();
var Apparelfound = ReferenceViewList.Where(x => x.SecCode == "APCODE" &&
string.IsNullOrEmpty(x.EntryValue) == false).FirstOrDefault();
if (Apparelfound != null)
{
ddlGarmentList.Enabled = true;
LoadGarments(Apparelfound.EntryValue);
}
else
{
ddlGarmentList.Enabled = false;
}
}
private void ConstructStyleNo()
{
foreach (ComponentReferenceView item in ReferenceViewList)
{
ReferenceLookUpList.Where(row => row.SecCode == item.SecCode).ToList()
.ForEach(refItem => refItem.EntryValue = item.EntryValue);
}
string sResult = string.Empty;
var result = (from x in ReferenceLookUpList.OrderBy(y => y.InOrder)
select x.EntryValue);
txtNewStyleNo.Text = string.Empty;
if (result != null)
txtNewStyleNo.Text = String.Join("", result) + "0001";
}
private void ConstructStyleDescription()
{
txtStyleDescription.Text = ddlBrandList.SelectedItem.Text + "-" + ddlGarmentList.SelectedItem.Text;
}
protected void ddlGarmentList_SelectedIndexChanged(object sender, EventArgs e)
{
txtStyleDescription.Text = string.Empty;
if (string.IsNullOrEmpty(ddlGarmentList.SelectedValue) == false)
ConstructStyleDescription();
}
}
ASPX:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="upnlNewFabrication" runat="server">
<ContentTemplate>
<h1>
New Style Item
</h1>
<br />
<%--<usrCtrl:style_generation ID="stylegen_frm" runat="server">
</usrCtrl:style_generation>--%>
<table>
<tr>
<td>
Brand :
</td>
<td>
<asp:DropDownList ID="ddlBrandList" runat="server"
onselectedindexchanged="ddlBrandList_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
Generated Style# :
</td>
<td>
<asp:TextBox ID="txtNewStyleNo" runat="server" ReadOnly="true"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Style Description :
</td>
<td>
<asp:TextBox ID="txtStyleDescription" runat="server" ReadOnly="true"></asp:TextBox>
</td>
</tr>
<asp:Repeater ID="rptStyleComponents" runat="server"
onitemdatabound="rptStyleComponents_ItemDataBound"
onitemcreated="rptStyleComponents_ItemCreated"
EnableViewState="True">
<ItemTemplate>
<asp:UpdatePanel ID="upnlComponent" runat="server">
<ContentTemplate>
<tr>
<td>
<asp:Label ID="lblSectionName" runat="server" Text='<%# Eval("SecName")%>' ></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlDataSelection" runat="server">
</asp:DropDownList>
</td>
</tr>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ddlDataSelection" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
</asp:Repeater>
</table>
<br />
<table>
<tr>
<td colspan="2">Description Items</td>
</tr>
<tr>
<td colspan="4"></td>
</tr>
<tr>
<td>Garment Type:</td>
<td>
<asp:UpdatePanel ID="upGarment" runat="server" >
<ContentTemplate>
<asp:DropDownList ID="ddlGarmentList" runat="server"
AppendDataBoundItems="True" AutoPostBack="True"
onselectedindexchanged="ddlGarmentList_SelectedIndexChanged">
<asp:ListItem Text = "Select garment" Value = ""></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sdsGarment" runat="server"
ConnectionString="<%$ ConnectionStrings:IRMSConnectionString %>"
SelectCommand="Select * from Garments"></asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ddlGarmentList" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td>Cost Price:</td>
<td>
<asp:TextBox ID="txtCostPrice" runat="server"></asp:TextBox></td>
<td>SRP :</td>
<td><asp:TextBox ID="txtSRP" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Quantity :</td>
<td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
<td>Week :</td>
<td><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
I have created user control named CRE.ascx,this control has 3 dropdownlist.
First dropdownlist bind data on pageload.Second and third based on SelectedIndexChanged.
<table cellspacing="0" cellspading="0" style="width:550px;height:30px;">
<tr>
<td style="width:30%;">
<asp:DropDownList ID="ddlCRE" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlCRE_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlDataPoints" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlDataPoints_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlErrorCode" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlErrorCode_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:10%;">
<asp:TextBox ID="tbxErrorScore" runat="server" style="height:17px;border:0px;font-family:'Segoe UI';font-size:13px;font-weight:500;color:white;background-color:#333333;
width:65px;" ReadOnly="true"> </asp:TextBox>
</td>
</tr>
</table>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Get Ticket Type Values
dbtickettype = helpdsktcktusrHandler.GetTicketType("DPT0001");
ddlCRE.DataSource = dbtickettype;
ddlCRE.DataValueField = "Type_ID";
ddlCRE.DataTextField = "Type_Name";
ddlCRE.DataBind();
ddlCRE.Items.Insert(0, new ListItem("Select Type", "SLCT0000"));
}
else
{
}
}
protected void ddlCRE_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedTypeID = ddlCRE.SelectedValue.ToString();
try
{
if (selectedTypeID == "SLCT0000")
{
ddlDataPoints.Items.Clear();
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketCategory = helpdsktcktusrHandler.GetTicketCategoryDetails(selectedTypeID);
//Binding Ticket Type values to Listbox
ddlDataPoints.DataSource = dbticketCategory;
ddlDataPoints.DataValueField = "Category_ID";
ddlDataPoints.DataTextField = "Category_Name";
ddlDataPoints.DataBind();
ddlDataPoints.Items.Insert(0, new ListItem("Select Category", "SLCT0000"));
//Clear Items
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlDataPoints_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCatID = ddlDataPoints.SelectedValue.ToString();
try
{
if (selectedCatID == "SLCT0000")
{
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketSubCategory = helpdsktcktusrHandler.GetTicketSubCategoryDetails(selectedCatID);
//Binding Ticket Type values to Listbox
ddlErrorCode.DataSource = dbticketSubCategory;
ddlErrorCode.DataValueField = "Sub_Category_ID";
ddlErrorCode.DataTextField = "Sub_Category_Name";
ddlErrorCode.DataBind();
ddlErrorCode.Items.Insert(0, new ListItem("Select Subcategory", "SLCT0000"));
//Clear Items
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlErrorCode_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedSubcatID = ddlErrorCode.SelectedValue.ToString();
try
{
if (selectedSubcatID == "SLCT0000")
{
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketIssues = helpdsktcktusrHandler.GetTicketIssueDetails(selectedSubcatID);
////Binding Ticket Type values to Listbox
//ddlstIssue.DataSource = dbticketIssues;
//ddlstIssue.DataValueField = "IssueID";
//ddlstIssue.DataTextField = "Issue_Name";
//ddlstIssue.DataBind();
tbxErrorScore.Text = dbticketIssues.Rows[0][1].ToString();
}
}
catch (Exception ex)
{
}
}
then register directive and an instance of the user control added to the page.
In this main page, i have added one Gridview, user control UC1 and two buttons
included in the ItemTemplate.
<%# Register src="~/CRE.ascx" TagName="InsertNewCRE" TagPrefix="uc1" %>
<asp:UpdatePanel ID="MainUpdatePanel" runat="server">
<ContentTemplate>
<div id="dvsubCRE" class="dvsubCRE" runat="server">
<!-----[[[ GRIDVIEW ADDING CRE ]]]----->
<div id="dvAddingErrorInfo" class="dvAddingErrorInfo">
<!-- LOAD CRE DROPDOWN INFO GRID -->
<asp:GridView ID="gvCREInfo" runat="server" CssClass="gvErrorInfo" AlternatingRowStyle-CssClass="" ShowFooter="false" ShowHeader="false"
EnableViewState="True" GridLines="None" EmptyDataText="No records found" AutoGenerateColumns="true" CaptionAlign="Left" CellPadding="0"
ShowHeaderWhenEmpty="True" OnRowCreated="gvCREInfo_RowCreated" OnRowCommand="gvCREInfo_RowCommand" >
<Columns>
<asp:BoundField DataField="RowNumber" />
<asp:TemplateField ItemStyle-Width="25%" ItemStyle-Height="20px">
<ItemTemplate>
<uc1:InsertNewCRE id="UC1InserCRE" runat="server" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgbtnAddCRE" runat="server" Width="20px" Height="20px" value="" ImageUrl="~/Images/Tracker/add.png"
CommandName="ButtonAddCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:ImageButton ID="imgbtnReoveCRE" runat="server" Width="20px" Height="20px" value="" Visible="false" ImageUrl="~/Images/Tracker/delete.png" CommandName="ButtonRemoveCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- LOAD CRE DROPDOWN INFO GRID CLOSE -->
</div>
<!-----[[[ GRIDVIEW ADDING CRE CLOSE ]]]----->
</div>
</ContentTemplate>
</asp:UpdatePanel>
When main page loads, user control UC1 loaded in the gridview and pull out the data from CRE.ascx page.I have bind dummy data on page load to the gridview.Add new row along with user control mentioned in the RowCommand.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
gvCREInfo.DataSource = dt;
gvCREInfo.DataBind();
}
else
{
}
}
catch (Exception ex)
{
}
}
protected void gvCREInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
#region ADD NEW CRE ROW
if (e.CommandName == "ButtonAddCRERow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvCREInfo.Rows[index];
int count = gvCREInfo.Rows.Count;
DataRow drCurrentRow = null;
UserControl UC1 = (UserControl)(row.Cells[0].FindControl("UC1InserCRE"));
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
for (int i = 0; i <= (count - 1); i++)
{
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
}
gvCREInfo.DataSource = dtCurrentTable;
gvCREInfo.DataBind();
}
#endregion
}
When i run this code working fine and i changed the first dropdownlist
it will pull data and bind to the second, like wise third one also.But when i click the add button selected data lost in the first row and second row control added not with data.How to retain existing selected data and load user control along with data it should not loss data event post back.Please help me and sort out this.
![enter image description here][1]
http://i.stack.imgur.com/wdYZv.jpg
I want to get values from user control
I tried but loop comes out
Code:
.aspx
<asp:Repeater ID="rpt1" runat="server">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnSaveVisa" Text="Save" runat="server" OnClick="btnSaveVisa_Click" />
AddVisaUserControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
<tr>
<td>
<asp:Label ID="lbl2" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td> Visa Number:</td>
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td> Country Name:</td>
<td><asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Type of Visa:</td>
<td><asp:DropDownList ID="dropVisa" Width="165px" runat="server"></asp:DropDownList></td>
<td> Type of Entry:</td>
<td><asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Expiry Date</td>
<td>
</td>
</tr>
</table>
</div>
.aspx.cs
public void generateControls()
{
for (int i = 0; i < int.Parse(ViewState["ControlCount"].ToString()); i++)
{
Label lbl = new Label();
string count = Convert.ToString(i + 1);
lbl.Text = "Visa" + count;
rpt1.Controls.Add(lbl);
rpt1.Controls.Add(LoadControl("VisaUserControl.ascx"));
rpt1.Controls.Add(new LiteralControl("<BR>"));
}
}
protected void btnAddVisa_Click(object sender, EventArgs e)
{
ViewState["ControlCount"] = int.Parse(ViewState["ControlCount"].ToString()) + 1;
generateControls();
}
//Here is the problem when I read the values from control the loop comes out
private void saveData()
{
for (int i = 0; i < this.rpt1.Controls.Count; i++)
{
if (this.rpt1.Controls[i] is TextBox)
{
TextBox txtserial = (TextBox)this.rpt1.Controls[i];
string value = txtserial.Text;
}
}
}
protected void btnSaveVisa_Click(object sender, EventArgs e)
{
saveData();
}
Any ideas? Thanks in advance
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
GenerateControls();
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
var ctrl = (AddVisaUserControl)LoadControl(#"AddVisaUserControl.ascx");
ctrl.ID = i;
this.AddVisaPlaceHolder.Controls.Add(ctrl); // Add in placeholder
}
}
//Adding controls to Place Holder
protected void AddButton_Click(object sender, EventArgs e)
{
List<string> temp = null;
var uc = (AddVisaUserControl)this.LoadControl(#"AddVisaUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
AddVisaPlaceHolder.Controls.Add(uc);
}
//Save
protected void Save_Click(object sender, EventArgs e)
{
foreach (var control in AddVisaPlaceHolder.Controls)
{
var usercontrol = control as AddVisaUserControl;
//you can access properties from usercontrol
//Implement save logic here
}
}
I am making a menu for a cafe. It shows the food and rinks items, the price and then I want a textbox, where people can write how much of each they want to buy, shown in a textbox. Then I want each textbox to have a unique ID based on the menu items ID.
This is my repeater:
<asp:Repeater ID="ParentRepeater" runat="server" OnItemDataBound="ParentRepeater_ItemDataBound">
<ItemTemplate>
<h2>
<%#DataBinder.Eval(Container.DataItem, "typenavn") %></h2>
<asp:HiddenField ID="HiddenField1" Value='<%# Eval("id") %>' runat="server" />
<asp:Repeater ID="ChildRepeater" runat="server">
<ItemTemplate>
<table>
<tr>
<td style="width: 400px">
<%#DataBinder.Eval(Container.DataItem, "productName") %>
</td>
<td style="width: 400px">
<%#DataBinder.Eval(Container.DataItem, "pris") %>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
And this is my code behind:
protected void ParentRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Repeater ChildRepeater = (Repeater)item.FindControl("ChildRepeater");
HiddenField hide = e.Item.FindControl("HiddenField1") as HiddenField;
int id = Convert.ToInt32(hide.Value);
var query = from es in gr.products
where es.typeID == id
select es;
List<product> list = new List<product>();
foreach (product pro in query)
{
list.Add(pro);
}
ChildRepeater.DataSource = list;
ChildRepeater.DataBind();
int h = 0;
foreach (RepeaterItem item1 in ChildRepeater.Items)
{
if (item1.ItemType == ListItemType.Item || item1.ItemType == ListItemType.AlternatingItem)
{
TextBox txt = (TextBox)item1.FindControl("TextBox1") as TextBox;
HiddenField hf = (HiddenField)item1.FindControl("HiddenField2") as HiddenField;
for (int i = 0; i < list.Count; i++)
{
txt.ID = "HB" + list[h].id.ToString();
hf.Value = list[h].id.ToString();
h++;
break;
}
}
}
}
}
Anybody got any ideas about how to find the textbox??
You have to search for the TextBox in the RepeaterItem. So you either handle the inner Repeater's ItemDataBound event or you simply iterate all RepeaterItems:
foreach(RepeaterItem item in ChildRepeater.Items){
if(item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem){
var txt = (TextBox)item.FindControl("TextBox1");
}
}