How to set a DataList.SelectedItem equal to a uniqeItemId - c#

I have a list of objects called dashboard which holds a list of Announcements with their AnnouncementId. My DataListAnnouncements.DataSource is equal to the dashboard but I can't figure out how to get the selectedItem equal to the item that I am selecting in the client side.
What Currently is happening is when I select an unread announcement, it displays the message with some css, but it does that to the wrong announcement at the moment.
protected void DataListAnnouncements_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Select")
{
IList<DashBoardView> dashboard = new List<DashBoardView>();
dashboard = (IList<DataObjects.DashBoardView>)ListOfObjects;
UnreadAnnouncement unread = UnreadAnnouncements;
if (e.CommandArgument != null)
{
if (unread != null)
{
unread.WasRead = true;
UpdateUnreadAnnouncement(unread);
att = unread.AnnouncementId;
}
}
dashboard[e.Item.ItemIndex].WasRead = unread.WasRead;
DataListAnnouncements.DataSource = Session["dashboard"];
DataListAnnouncements.SelectedItem = dashboard[e.Item.ItemIndex]
(DataListAnnouncements.SelectedItem = att <---- Something Like this is what I would like to implement?)
Session["dashboard"] = dashboard;
bindDataList();
}
}
as you see now, I have it using the dashboard[e.Item.ItemIndex].WasRead = unread.WasRead line, but this proves to not work since the index is not always what I want. So I want to use an attribute. I looked around a bit but I am still fuzzy on how to implement it on the C# and asp side.
and this is my ASP.
<ItemTemplate>
<table width="880px">
<tr>
<td class="leftCol">
<asp:LinkButton Text='<%# Eval("title") %>' CssClass="bold" runat="server" CommandName="Select" CommandArgument='<%# Eval("UnreadAnnouncementId") %>' ID="titleLabel" /></span>
</td>
<td class="created">
<asp:Label Text='<%# DataBinder.Eval(Container.DataItem, "Effective", "{0:MM/dd/yyyy}") %>' CssClass="created" runat="server" ID="Label4" />
<br />
<asp:Label Text='<%# Eval("FirstName") %>' runat="server" ID="Label2" />
<asp:Label Text='<%# Eval("LastName") %>' runat="server" ID="Label3" />
</td>
</tr>
<tr>
<td class="one-long-line">
<asp:Label Text='<%# Eval("details") %>' CssClass="details" runat="server" ID="detailsLabel" />
</td>
</tr>
</table>
</ItemTemplate>
<SelectedItemTemplate>
<table width="880px" cellpadding="10px">
<tr>
<td class="leftCol">
<asp:Label Text='<%# Eval("title") %>' CssClass="bold" runat="server" ID="titleLabel" />
<asp:Label runat="server" ID="wasRead" Text='<%# Eval("wasRead") %>' Visible="false" Enabled="false" />
<td class="created">
<asp:Label Text='<%# DataBinder.Eval(Container.DataItem, "Effective", "{0:MM/dd/yyyy}") %>' CssClass="created" runat="server" ID="Label4" />
<br />
<asp:Label Text='<%# Eval("FirstName") %>' runat="server" ID="Label2" />
<asp:Label Text='<%# Eval("LastName") %>' runat="server" ID="Label3" />
</td>
</tr>
<tr>
<td class="deailsTD" colspan="2">
<asp:Label Text='<%# Eval("details") %>' CssClass="details" runat="server" ID="detailsLabel" />
</td>
</tr>
<tr>
</tr>
</table>
</SelectedItemTemplate>
I want to be able to click on a item in the datagrid, and it will expand that item and show me the details.

You have to use `SelectedIndex', not SelectedItem'. Source: How to: Allow Users to Select Items in DataList Web Server Controls.
It could be like this:
DataListAnnouncements.SelectedIndex = e.Item.ItemIndex;
From your code it is not clear what is the relation between dashboard and att. If there's any way to find the att in dashboard and find it's position, you can do like this:
DataListAnnouncements.SelectedIndex = attposition;
EDIT : There's an easy way to control background color of DataLists Items. We can parse each item in DataList's ItemBound and set BackColor like below:
protected void DataListAnnouncements_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem||
e.Item.ItemType == ListItemType.SelectedItem
)
{
// Here BackColor - Grey: WasRead; Yellow: Unread
var wasRead = ((DashBoardView)e.Item.DataItem).WasRead;
e.Item.BackColor = wasRead? System.Drawing.Color.Gray: System.Drawing.Color.Yellow;
}
}
You can even expand it more by splitting the if condition into two:
if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem){}
and
if ( e.Item.ItemType == ListItemType.SelectedItem){}

Related

Repeater Item can't find NamingContainer

I recently switched a ComboBox in my repeater to a SuggestComboBox (found: here) because it is a contains search rather than a starts-with search. Previously, I was using NamingContainer of that ComboBox to find nearby elements. My new SuggestComboBox does not have this value but in my research on this problem, it looks like all children of a repeater should have this already?
"the NamingContainer property is available in code to any instance of that class or of a derived class." (found: here)
What am I missing?
Here's my repeater:
<asp:Repeater ID="repHW" runat="server" OnItemCommand="rep_ItemCommand">
<HeaderTemplate>
<table style="width:100%; padding-bottom:10px" id="HWtable">
<tr style="font-weight: bold"><td>Product</td><td>Part Number</td><td>Cost</td><td>Unit Price</td><td>Quantity</td><td>Price</td><td>Delete</td></tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<asp:HiddenField ID="Category" Value="Hardware" runat="server"/>
<td><asp:Label ID="Product" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Product.Name") %>' /></td> <!--TODO: make this clickable to edit -->
<td><asp:Label ID="PartNumber" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Product.PartNumber") %>' /></td>
<td><asp:Label ID="PartCost" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Product.Cost") %>' /></td>
<td><asp:Label ID="UnitPrice" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Product.Price") %>' /></td>
<td><asp:Label ID="Quantity" runat="server" Text='<%# Eval("Quantity") %>' /></td>
<td><asp:Label ID="Price" runat="server" Text='<%# Eval("Total") %>' /></td>
<td><asp:Button class="btn btn-danger" ID="DeleteHardware" runat="server" Text="Delete" CommandName="Delete" CommandArgument='<%# Container.ItemIndex %>'/></td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr>
<asp:HiddenField ID="AddCategory" Value="Hardware" runat="server"/>
<td><SuggestComboBox runat="server" ID="AddProduct" AutoCompleteMode="SuggestAppend" AutoPostBack="true" OnSelectedIndexChanged="ProductSelected" OnDataBinding="LoadHardwareProducts"/></td>
<td><asp:TextBox runat="server" ID="AddPartNumber" ClientIDMode="static"/></td>
<td><asp:TextBox runat="server" ID="AddPartCost" ClientIDMode="static"/></td>
<td><asp:TextBox runat="server" ID="AddUnitPrice" ClientIDMode="static"/></td>
<td><asp:TextBox runat="server" ID="AddQuantity" ClientIDMode="static"/></td>
<td><asp:Button class="btn btn-success" ID="AddHardware" runat="server" Text="Add" CommandName="Add" CommandArgument='<%# Container.ItemIndex %>' onClientClick="return EmptyFieldCheck('Hardware');"/></td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
and here's my function I am trying to access the other elements in:
protected void ProductSelected(Object source, EventArgs e)
{
SuggestComboBox temp = (SuggestComboBox)source;
List<Product> results = session.Query<Product>()
.Where(x => x.Name == temp.Text)
.ToList();
if(results.Count > 0)
{
Product p = results[0];
var repParent = temp.NamingContainer; //this broke
TextBox partNum = (TextBox)repParent.FindControl("AddPartNumber");
TextBox partCost = (TextBox)repParent.FindControl("AddPartCost");
TextBox unitPrice = (TextBox)repParent.FindControl("AddUnitPrice");
TextBox quantity = (TextBox)repParent.FindControl("AddQuantity");
partNum.Text = p.PartNumber;
partCost.Text = p.Cost.ToString();
unitPrice.Text = p.Price.ToString();
quantity.Text = p.DefaultQuantity.ToString();
}
}

Change header text in Rowdataboud of Gridview nested inside Repeater

I have a gridview nested inside a repeater, I want to change the header text of gridview columns on row databound or through
<HeaderTemplate>
<asp:Label runat="server" ID="lblMode" Text='<%# Eval("IsValidForPromoCode")%>'>
</asp:Label></HeaderTemplate>
whichever is convenient.
.aspx page
<asp:Repeater ID="repRequest" runat="server" OnItemDataBound="repRequest_ItemDataBound">
<ItemTemplate>
<table style="width: 100%; font-weight: bold;" cellpadding="5" cellspacing="0">
<tr>
<td colspan="12" align="right">
<a id="aSetPreference" runat="server" href="#">Attached Document(s)-</a>
<asp:Label ID="lblDocumentCount" CssClass="redFont" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="left" class="gray-bg" style="width: 8%;">
<b>Request#:</b>
</td>
<td style="width: 100px;">
<span class="detail-info-color">
<%# Eval("RequestNumber")%></span>
</td>
<td align="left" class="gray-bg" style="width: 5%;">
<asp:Label ID="lblreqDetID" runat="server" Visible="false" Text='<%# Bind("TravelDetailsID") %>'></asp:Label>
<b>Date:</b>
</td>
<td align="left" class="gray-bg" style="width: 5%;">
<b>Class:</b>
</td>
<td>
<span class="detail-info-color">
<%# Eval("Class")%></span>
</td>
</tr>
<tr>
<td colspan="12">
<asp:GridView ID="gvOption" CssClass="gridRow" runat="server" AutoGenerateColumns="False"
Width="100%" OnRowDataBound="gvOption_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="#">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Service Provider">
<ItemTemplate>
<asp:Label ID="txtNumber" runat="server" Width="80px" Text='<%# Bind("Number") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label runat="server" ID="lblMode" Text='<%# Eval("IsValidForPromoCode") %>'></asp:Label></HeaderTemplate>
<ItemTemplate>
<asp:Label ID="txtName" runat="server" Width="100px" Text='<%# Bind("Name") %>'></asp:Label>
<asp:Label ID="lblOptionID" Visible="false" runat="server" Width="100px" Text='<%# Bind("optionID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Code behind
protected void gvOption_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
GridView gvOption = (GridView)sender;
if (e.Row.RowType == DataControlRowType.DataRow)
{
gvOption.Columns[1].HeaderText = "Last Name";
}
if (e.Row.RowType == DataControlRowType.Header)
{
gvOption.Columns[2].HeaderText = "Last Name";
}
}
catch (Exception ex)
{
throw ex;
}
}
Whichever way I am doing it's not effecting. Please suggest what I am missing.
Try this:-
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[1].Text = "Last Name";
}
Here, I have hard-coded the Cells value you need to change it accordingly.
Update:-
Find Control inside RowDataBound:-
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label txtNumber = (Label)e.Row.FindControl("txtNumber");
txtNumber.ForeColor = System.Drawing.Color.Red;
}

How I an bind a DataSource to a DropDownList in a dynamic ListView in ASP.NET with C#?

I have a ASP.NET Application and use the ListView Control. For binding this ListView I use a DataTable object and my ListView have th follow structure:
<asp:listView ...>
<LayoutTemplate>
<ItemTemplate>
<AlternatingItemTemplate>
I use in the ItemTemplate and AlternatingItemTemplate a DropDownList. This must me show the Location. I use a XML File for this with XmlDataSource Control. But now is the Problem I must update my XML File in the code and delete Elements that I have only Special Elements for the Active user. That means the DropDoanList Control in my ListView don't show all Elements in the XML File.
So I think I can create first the DataTable Object. Then I bind this with the ListView and after this I Find The Control in the ListView. But I get everytime "null" :( . I dont find this object.
here is my code:
ListView.DataSource = tb;
ListView.DataBind();
XDocument x = XDocument.Load(Server.MapPath(#"~\App_Data\location.xml"));
string ActiveUser = GetUsername();
ArrayList ListOfNPSGroups = GetGroupsInOUByValue();
ArrayList ActiveUserList = GetGroupmemberList(ListOfNPSGroups);
x.Root.Descendants()
.Where(d => !ActiveUserList.Contains((string)d.Attribute("group")))
.ToList()
.ForEach(s => s.Remove());
var data = (from item in x.Elements("plants").Elements("plant")
select new { display = item.Attribute("display").Value, id = item.Attribute("id").Value }).ToList();
DropDownList ListViewDropDownListLocation = (DropDownList)ListView.FindControl("ListViewDropDownListLocation"); // here I get NULL
ListViewDropDownListLocation.DataSource = data;
ListViewDropDownListLocation.DataTextField = "display";
ListViewDropDownListLocation.DataValueField = "id";
ListViewDropDownListLocation.DataBind();
Here I show my ASPX:
<ItemTemplate>
<tr id="Tr1" class="TableClassO" runat="server" onmouseover="this.style.backgroundColor='#87CEFA'"
onmouseout="this.style.backgroundColor='#ffffff'" titel="Auswahl">
<td>
<asp:DropDownList ID="drpDeviceClass" runat="server" SelectedValue='<%# Eval("DeviceClass") %>' DataTextField="display" DataValueField="id" DataSourceID="xmlDeviceClass" Width="90%" >
</asp:DropDownList>
<asp:XmlDataSource ID="xmlDeviceClass" runat="server" DataFile="~/App_Data/devices.xml" ></asp:XmlDataSource>
</td>
<td >
<asp:TextBox ID="txtMacAdress" runat="server" Text='<%# Eval("MAC") %>' Width="90%"></asp:TextBox>
</td>
<td >
<asp:DropDownList ID="ListViewDropDownListLocation" SelectedValue='<%# Eval("Location") %>' runat="server" Width="90%"
DataTextField="display" DataValueField="id" DataSourceID="ListViewXMLRessourceLocation"></asp:DropDownList>
<asp:XmlDataSource ID="ListViewXMLRessourceLocation" runat="server" DataFile="~/App_Data/location.xml" ></asp:XmlDataSource>
</td>
<td >
<asp:TextBox ID="txtFirstname" runat="server" Text='<%# Eval("Vorname") %>' Width="90%"></asp:TextBox>
</td>
<td >
<asp:TextBox ID="txtLastname" runat="server" Text='<%# Eval("Nachname") %>' Width="90%"></asp:TextBox>
</td>
<td >
<asp:TextBox ID="txtDescription" runat="server" Text='<%# Eval("Beschreibung") %>' Width="90%"></asp:TextBox>
</td>
<td>
<asp:ImageButton ID="imgSaveOnly" ImageAlign="Middle" runat="server" CommandName="Save" CommandArgument='<%# Container.DataItemIndex %>' Width="15" Height="15" ImageUrl="~/App_Themes/Images/Save-icon.png" ToolTip="Eintrag ins Active Directory übernehmen" />
</td>
<td>
<asp:ImageButton ID="imgPowerShell" ImageAlign="Middle" runat="server" CommandName="Powershell" CommandArgument='<%# Container.DataItemIndex %>' Width="15" Height="15" ImageUrl="~/App_Themes/Images/ps.png" ToolTip="PowerShell Befehl Anzeigen" />
</td>
<td>
<asp:ImageButton ID="imgDelete" runat="server" ImageAlign="Middle" CommandName="Delete" CommandArgument='<%# Container.DataItemIndex %>' Width="15" Height="15" ImageUrl="~/App_Themes/Images/delete.png" ToolTip="Eintrag Löschen" />
</td>
</tr>
</ItemTemplate>
Ho I can solve this Problem :/ ?
In which event are you trying to find the control? You could try to do the location dropdown part in the ItemDataBound event and use this code (needs some refactoring to not get data multiple times probably)
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
XDocument x = XDocument.Load(Server.MapPath(#"~\App_Data\location.xml"));
string ActiveUser = GetUsername();
ArrayList ListOfNPSGroups = GetGroupsInOUByValue();
ArrayList ActiveUserList = GetGroupmemberList(ListOfNPSGroups);
x.Root.Descendants().Where(d => !ActiveUserList.Contains((string)d.Attribute("group")))
.ToList()
.ForEach(s => s.Remove());
var data = (from item in x.Elements("plants").Elements("plant")
select new { display = item.Attribute("display").Value, id = item.Attribute("id").Value }).ToList();
HiddenField hidden = e.Item.FindControl("HiddenField1") as HiddenField;
if (hidden != null && !string.IsNullOrEmpty(hidden.Value))
{
DropDownList listViewDropDownListLocation = e.Item.FindControl("ListViewDropDownListLocation") as DropDownList;
listViewDropDownListLocation.DataSource = data;
listViewDropDownListLocation.DataTextField = "display";
listViewDropDownListLocation.DataValueField = "id";
listViewDropDownListLocation.DataBind();
listViewDropDownListLocation.SelectedValue = hidden.Value;
}
}
And in the .aspx replace the locationdropdown with source to a simple dropdown and a hiddenfield to store the relevant location
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("Location") %>' />
<asp:DropDownList ID="ListViewDropDownListLocation" runat="server" Width="90%" />

getting datediff/timespan between records

Let's say I have a basic asp.net C# web app where I enter the dates of different events, say oil changes, for example. And I want to track this for different vehicles. And then I want to calculate the difference in days between oil changes.
So for the most recent oil change, the datediff/timespan would calculate from today. But for previous oil changes, I want the datediff/timespan to calculate between each previous record in the recordset. I could, I suppose, create a field to put the number of days in there, but I think it should be easy to do programmatically, no?
Now, in classic ASP, I'd do something like this (in fact, this is what I do in the previous version of this little app):
<%set rs=conn.Execute("select vehiclename,changedate from oilchange order by changedate desc")
do until rs.EOF
dim recordchk,record
recordchk = record
date2=date1
date1=rs("changedate")
if record <> rs("vehcilename") then
record = rs("vehiclename")
end if%>
<%
if record <> recordchk then
%>
<tr><td colspan="9"><hr color="black"/></td></tr>
<tr><td colspan="9"><b><%=rs("vehiclename") %></b></td></tr>
<tr><td valign="top" width="15%"><%=rs("changedate") %> <i>(<%=datediff("d",rs("changedate"),date()) %> days)</i></td>
</tr>
<%else%>
<tr><td valign="top" width="15%"><%=rs("changedate") %> <i>(<%=datediff("d",rs("changedate"),date2) %> days)</i></td>
</tr>
<%end if%>
<%rs.MoveNext
loop
rs.Close
%>
But I'm stumped how to do in in ASP.NET
For the different vehicles I have a repeater, then I nest a repeater inside to run through the oil change records for that vehicle. Runs through the list of oil changes just fine, but I can't figure out how to do the calculation to get me the days between oil changes.
So, here's my codebehind... (you can see that it's not oil changes, but guitar string changes.)
protected void guitarrepeateritemdatabound(object sender, RepeaterItemEventArgs e)
{
stringsEntities db = new stringsEntities();
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
Repeater StringChangeRepeater = (Repeater)e.Item.FindControl("StringChangeRepeater");
HiddenField guitarIDfield = (HiddenField)e.Item.FindControl("guitarIDint");
int guitarIDint = Convert.ToInt32(guitarIDfield.Value);
Label changedate = (Label)e.Item.FindControl("changedate");
TimeSpan timeBetweenChanges = (DateTime.Now - Convert.ToDateTime(changedate));
var qrystringchangesview = (from s in db.stringchange_view
where s.guitarid == guitarIDint
orderby s.changedate descending
select new
{
guitarID2 = s.guitarid,
s.guitarname,
s.stringname,
s.changedate,
s.gauge
});
StringChangeRepeater.DataSource = qrystringchangesview;
StringChangeRepeater.DataBind();
and then my aspx page:
<asp:Repeater ID="GuitarRepeater" runat="server" OnItemDataBound="guitarrepeateritemdatabound">
<ItemTemplate>
<tr>
<td valign="top">
<asp:HiddenField ID="guitarIDint" runat="server" Value='<%# Eval("guitarID") %>' />
<asp:LinkButton OnClick="clicktheinstrument" ID="guitarname" runat="server" Font-Bold="true" CommandArgument='<%#Eval ("guitarID") %>' Text='<%# Eval("guitarname") %>' />
<asp:Repeater runat="server" ID="StringChangeRepeater">
<ItemTemplate>
<table><tr><td style="width:100px">
<asp:Label ID="changedate" runat="server" Text='<%# Eval("changedate","{0:MM/dd/yyyy}") %>'></asp:Label>
(<asp:Label ID="timeBetweenChangesLabel" runat="server"></asp:Label>)
</td><td style="width:200px">
<asp:Label ID="stringname" runat="server" Text='<%# Eval("stringname") %>'></asp:Label>
</td><td style="width:100px">
<asp:Label ID="gauge" runat="server" Text='<%# Eval("gauge") %>'></asp:Label>
</td></tr></table>
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr style="background-color: #F7F7F7">
<td valign="top">
<asp:HiddenField ID="guitarIDint" runat="server" Value='<%# Eval("guitarID") %>' />
<asp:LinkButton OnClick="clicktheinstrument" ID="guitarname" runat="server" Font-Bold="true" CommandArgument='<%#Eval ("guitarID") %>' Text='<%# Eval("guitarname") %>' />
<asp:Repeater runat="server" ID="StringChangeRepeater">
<ItemTemplate>
<table><tr><td style="width:100px">
<asp:Label ID="changedate" runat="server" Text='<%# Eval("changedate","{0:MM/dd/yyyy}") %>'></asp:Label>
(<asp:Label ID="timeBetweenChangesLabel" runat="server"></asp:Label>)
</td><td style="width:200px">
<asp:Label ID="stringname" runat="server" Text='<%# Eval("stringname") %>'></asp:Label>
</td><td style="width:100px">
<asp:Label ID="gauge" runat="server" Text='<%# Eval("gauge") %>'></asp:Label>
</td></tr></table>
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
</AlternatingItemTemplate>
</asp:Repeater>
well, I got an answer over at asp.net forums... thought I'd post it here to help anyone else who's doing a similar thing.
foreach (RepeaterItem item in StringChangeRepeater.Items)
{
if (item.ItemType == ListItemType.Item || (item.ItemType == ListItemType.AlternatingItem))
{
HiddenField stringchangeIDHidden = item.FindControl("stringchangeID") as HiddenField;
int stringchangeID = Convert.ToInt32(stringchangeIDHidden.Value);
var getcurrentrecord = (from s in db.stringchange_view
where s.ID == stringchangeID
select new
{
s.changedate
}).First();
Label timeBetweenChangesLabel = item.FindControl("timeBetweenChangesLabel") as Label;
DateTime changedate1 = Convert.ToDateTime(getcurrentrecord.changedate);
TimeSpan changedateSpan = changedateX - changedate1;
TimeSpan changedateSpan2 = changedate1 - Convert.ToDateTime(getcurrentrecord.changedate);
timeBetweenChangesLabel.Text = changedateSpan.Days.ToString();
changedateX = changedate1;
}
}

Keeping prior values when using listview insert

Currently I have a gridview that when I click on select it populates values in a listview.
I handle this in code behind using the selectedindexchanged event. And I even populate a text box in the insertitem template for new entries.
protected void GridView9_SelectedIndexChanged(object sender, EventArgs e)
{
// this handles the transmittal costs
SqlDataSource29.SelectParameters.Clear();
SqlDataSource29.SelectParameters.Add("tc_t_id", App_id);
SqlDataSource29.InsertParameters.Clear();
ListView1.Visible = true;
ListView1.DataBind();
((TextBox)ListView1.InsertItem.FindControl("tc_t_idTextBox")).Text = App_id;
However the issue arises when I do an insert. I lose value I put into the listviews insertitem texbox tc_t_idTextBox. Actually I lose the value when I edit and delete also.
There must be a way to hold onto that value between inserts.
<InsertItemTemplate>
<tr style="">
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert"
Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Clear" />
</td>
<td>
<asp:TextBox ID="tc_dateTextBox" runat="server" Text='<%# Bind("tc_date") %>' />
</td>
<td>
<asp:TextBox ID="tc_costTextBox" runat="server" Text='<%# Bind("tc_cost") %>' />
</td>
<td>
<asp:TextBox ID="tc_typeTextBox" runat="server" Text='<%# Bind("tc_type") %>' />
</td>
<td>
<asp:TextBox ID="tc_commentTextBox" runat="server" Text='<%# Bind("tc_comment") %>' />
</td>
<td>
</td>
<td>
<asp:TextBox ID="tc_t_idTextBox" runat="server"
Text='<%# Bind("tc_t_id") %>' Enabled="false" Width="15" />
</td>
</tr>
</InsertItemTemplate>
By using DataBind() on every PostBack, the ListView is being reloaded every time the user performs and action. In the Page_Load of your page, do this instead:
SqlDataSource29.SelectParameters.Clear();
SqlDataSource29.SelectParameters.Add("tc_t_id", App_id);
SqlDataSource29.InsertParameters.Clear();
ListView1.Visible = true;
if(!IsPostBack)
{
ListView1.DataBind();
}
((TextBox)ListView1.InsertItem.FindControl("tc_t_idTextBox")).Text = App_id;

Categories

Resources