I know this is a quite common problem but I couldn't find a solution over internet yet. Maybe I got into a tunnel vision, I don't know.
I have a gridview and the dropdownlist related to it keeps resetting. It's been hours and I'm still having this problem.
The table which has the DropDownList
<table class="filtertable" EnableViewState="true">
<tr align="center">
<td width="100%">
<asp:Button ID="btnNew" runat="server" Text="Yeni Kayıt" OnClick="btnNew_OnClick"
CssClass="btn" Visible="true" />
<asp:Button ID="btnArama" runat="server" Text="Gümrük Arama" OnClick="btnArama_Click"
CssClass="btn" Visible="false" />
</td>
</tr>
<tr runat="server" id="trGumrukArama">
<td>
<fieldset style="margin-top: 5px">
<legend>Ülke Gümrük Arama</legend>
<table EnableViewState="true">
<tr>
<td>
<asp:Label runat="server" ID="lblUlke">Ülke: </asp:Label>
</td>
<td>
<asp:DropDownList runat="server" ID="drpUlke" AppendDataBoundItems="true" EnableViewState="true"
OnSelectedIndexChanged="drpUlke_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td>
<asp:Label runat="server" ID="lblGumrukKodu"> Gümrük Kodu:  </asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="txtGumrukKodu"></asp:TextBox>
</td>
<td>
<asp:Label runat="server" ID="lblGumrukAdi">Gümrük Adı:  </asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="txtGumrukAdi"></asp:TextBox>
</td>
<td>
<asp:Button runat="server" CssClass="btn" ID="btnSearch" Text="Ara" OnClick="btnSearch_OnClick" />
</td>
</tr>
</table>
</fieldset>
</td>
</tr>
</table>
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
drpUlke_Bind();
BindList();
//drpUlke.SelectedValue = ViewState["ListUlkeKod"].ToString();
}
}
protected void drpUlke_Bind()
{
DataTable dt = CacheManager.UlkelerGercek.Tables[0];
DataTable dtNew = CacheManager.UlkelerGercek.Tables[0].Clone();
DataRow drseperator = dtNew.NewRow();
drseperator["id"] = -1;
drseperator["harfKod"] = "";
drseperator["adi"] = "------------------------------------";
dtNew.Rows.Add(drseperator);
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dtNew.NewRow();
dr.ItemArray = dt.Rows[i].ItemArray;
dr["adi"] = dr["harfKod"] + " - " + dr["adi"];
if (dr["harfKod"].ToString().Trim() == "TR")
dtNew.Rows.InsertAt(dr, 0);
else
dtNew.Rows.Add(dr);
}
drpUlke.DataSource = dtNew;
drpUlke.DataValueField = "harfKod";
drpUlke.DataTextField = "adi";
drpUlke.DataBind();
drpKaydetUlke.DataSource = dtNew;
drpKaydetUlke.DataValueField = "harfKod";
drpKaydetUlke.DataTextField = "adi";
drpKaydetUlke.DataBind();
}
protected void drpUlke_SelectedIndexChanged(object sender, EventArgs e)
{
}
.
.
.
.
.
private void BindList()
{
int TotalCount;
int Start = (CurrentPageIndex - 1) * _pageRowCount;
string UlkeKodu = drpUlke.SelectedValue;
//ViewState["ListUlkeKod"] = UlkeKodu;
string GumrukKodu = txtGumrukKodu.Text;
string GumrukAdi = txtGumrukAdi.Text;
//drpUlke.SelectedValue = ViewState["ListUlkeKod"].ToString();
DataSet ds = (Stored Procedure Here)
gvUlkeGumruk.DataSource = ds;
gvUlkeGumruk.DataBind();
int intTotalCount;
int intCurrentCount;
intTotalCount = TotalCount == -1 ? 0 : TotalCount;
intCurrentCount = ds.Tables[0].Rows.Count - 1;
pcBottom.TotalRowCount = intTotalCount;
pcBottom.PageRowCount = _pageRowCount;
pcBottom.CurrentRowCount = intCurrentCount;
pcBottom.BindPaging();
pcBottom.Visible = intTotalCount > 0;
}
Just the related parts, If I'm missing something please let me know.
I tried using viewstate variables but they kept getting resetted too.
edit:
I came across a few posts on internet about this problem. They were saying as a solution that their dropdown lists value field not being unique. I checked the value field and it's values are all unique.
When you want the DDL data to survive a postback you've got to reload the DDL during the postback lifecycle. You can do this manually, or enable ViewState which you'd have to do on the control chain.
If you go the manual route of loading data in control/page init (regardless of the IsPostBack flag) you can improve performance by making sure your data is cached. You'll be skipping the ViewState (good for client performance), but hitting your DB more. If that's a problem then you can go back to using ViewState.
This may happens because of AppendDataBoundItems="true". Removed that property and try again
The answers above are true on their own cases and not to be dismissed as incorrect. Due to the nature of my problem, I can't designate one as answer.
I ended up sending drop down choice as a request parameter to each other page. We are using a custom pagination mechanism and that is the reason I had to end up this way.
Related
How can I save rows created in the list view in my database? How can I access the values in the (list view)? How to save the values created in the view list to the database?
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate runat="server">
<tr class="text-center">
<td class="product-remove"></td>
<td class="image-prod">
<div class="">
<asp:Image ID="Image1" CssClass=" img" ImageUrl='<%# "../img/" + Eval("picture" )%>' runat="server" />
</div>
</td>
<td class="product-name"><%# Eval("namebook") %> </td>
<td id="t_Plural" runat="server" class="price "><%# Eval("Price") %> </td>
<td class="quantity"><%# Eval("titel") %></td>
<td class="col-2">
<asp:Button ID="delete" CssClass="btn btn-outline-danger" CommandArgument='<%# Eval("id")%>' OnClick="delete_Click" runat="server" Text="حذف کالا" />
</td>
<td>
<%-- <input id="quantity2" runat="server" type="number" AutoPostBack="true" oninput="lod_gheymat" onserverclick="lod_gheymat" value="" min="1" max="20" />--%>
<asp:TextBox ID="quantity2" runat="server" CssClass="input-wrap" AutoPostBack="true" OnTextChanged="lod_gheymat" Text="1" min="1" max="20"></asp:TextBox>
</td>
<td >
<div class="row">
<asp:Label ID="lbl_Plural" runat="server" Text="0"></asp:Label> <span class="row"> تومان</span>
</div>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
The way to approach this type of issue and problem is to NOT try and add to the database from the list view.
What you do is get your data (say in a data table).
then send the data table to the list view.
Now, if you want say a "add new row" button?
Add the row to the data table, and then re-bind the list view.
Next up?
You asking how to add this to the database, but is not that where it came form in the first place?
and it is VERY confusing that you asking how to add rows to this LV, but how is the user going to add the picture?
Next up, how is this post getting up-votes? I will assume up-votes are not being messed with? I'll put this issue aside, but something not fitting here.
Ok, so, how to add rows, and how to save such rows back to the database?
You can achieve this goal this way:
First, we assume the LV can now be freely edit. That means using text boxes.
so, we have this markup:
(probably not HUGE important the LV you have, but the "idea" outlined here should work fine).
<style> .borderhide input, textarea {border:none}</style>
<div style="width:70%;padding:20px">
<h2>Fighter Prints</h2>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
<ItemTemplate>
<tr style="">
<td><asp:TextBox ID="Fighter" runat="server" Text='<%# Eval("Fighter") %>' TextMode="MultiLine" /></td>
<td><asp:TextBox ID="Engine" runat="server" Text='<%# Eval("Engine") %>' TextMode="MultiLine" Width="200px" /></td>
<td><asp:TextBox ID="Thrust" runat="server" Text='<%# Eval("Thrust") %>' Width="70px" /></td>
<td><asp:TextBox ID="Description" runat="server" Text = '<%#Eval("Description") %>'
TextMode="MultiLine" Width="340px" Rows="5" /></td>
<td>
<asp:Image ID="iPreview" runat="server" Height="68px" Width="149px"
ImageUrl='<%# Eval("ImagePath") %>'/>
</td>
<td><asp:TextBox ID="Qty" runat="server" Text='<%# Eval("Qty") %>' style="width:30px;text-align:right"/></td>
<td><asp:TextBox ID="Price" runat="server" Text='<%# string.Format("{0:c2}",Eval("Price")) %>' style="Width:70px;text-align:right"/></td>
<td><asp:TextBox ID="Total" runat="server" Text='<%# string.Format("{0:c2}",Eval("Total")) %>' style="Width:70px;text-align:right" /></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server"
class="table table-hover borderhide ">
<tbody>
<tr runat="server" style="" >
<th runat="server">Fighter</th>
<th runat="server">Engine</th>
<th runat="server">Thrust (lbs)</th>
<th runat="server">Description</th>
<th runat="server">Preview</th>
<th runat="server" style="text-align:right">Qty</th>
<th runat="server" style="width:70px;text-align:right">Price</th>
<th runat="server" style="width:70px;text-align:right">Total</th>
</tr>
<tr id="itemPlaceholder" runat="server" />
</tbody>
<tfoot>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td><td>Total</td>
<td><asp:TextBox ID="MyTotal" runat="server" Text="0" Width="70px" Style="text-align:right"></asp:TextBox></td>
</tr>
</tfoot>
</table>
</LayoutTemplate>
</asp:ListView>
Ok, so the code to load is now this:
DataTable rstData = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
Session["rstData"] = rstData;
}
else
rstData = Session["rstData"] as DataTable;
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
{
conn.Open();
rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
rstData.Columns.Add("Total", typeof(decimal),"[Qty] * [Price]");
ListView1.DataSource = rstData;
ListView1.DataBind();
decimal myTotal = 0;
foreach (ListViewItem OneRow in ListView1.Items)
{
TextBox MyPrice = OneRow.FindControl("Total") as TextBox;
myTotal += Decimal.Parse(MyPrice.Text, NumberStyles.Currency);
}
// now update the final total label
TextBox lblTotal = ListView1.FindControl("MyTotal") as TextBox;
lblTotal.Text = string.Format("{0:c2}", myTotal);
}
}
}
And now we have this:
Ok, for the above, note how we added 3 buttons below the LV.
And becuase I wanted "cute" icons in the buttons, I dropped in hteml buttons, not asp.net ones. But, with a "id" and runat=server, they work JUST the same anyway.
So, our 3 buttons are (right after the LV markup)
<div style="float:left">
<button id="cmdSave" runat="server" class="btn" onserverclick="cmdSave_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-save"></span>  Save
</button>
<button id="cmdUndo" runat="server" class="btn" style="margin-left:10px" onserverclick="cmdUndo_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-retweet"></span>  Un do
</button>
</div>
<div style="float:right">
<button id="cmdAddNew" runat="server" class="btn" onserverclick="cmdAddNew_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-new-window"></span>  Add New
</button>
</div>
Ok, so of the 3, the un-do button code is easy:
protected void cmdUndo_ServerClick(object sender, EventArgs e)
{
// undo changes - just re-load the lv
LoadGrid();
}
Ok, now the save button. This save button will:
save any new rows, and ALSO save any editing we do. Remember, since we used text boxes, then I can quite much tab around - edit ANY row. If I hit save, then we save all edits AND ALSO any new row added.
So, the save button does this:
protected void cmdSave_ServerClick(object sender, EventArgs e)
{
GridToTable(); // send lv to table
SaveToDatabase();
}
So, now we need the routine to send the LV to the table. That code is this:
void GridToTable()
{
// pull grid rows back to table.
foreach (ListViewItem rRow in ListView1.Items)
{
int RecordPtr = rRow.DataItemIndex;
DataRow OneDataRow;
OneDataRow = rstData.Rows[RecordPtr];
OneDataRow["Fighter"] = ((TextBox)rRow.FindControl("Fighter")).Text;
OneDataRow["Engine"] = ((TextBox)rRow.FindControl("Engine")).Text;
OneDataRow["Thrust"] = ((TextBox)rRow.FindControl("Thrust")).Text;
OneDataRow["Description"] = ((TextBox)rRow.FindControl("Description")).Text;
OneDataRow["Qty"] = ((TextBox)rRow.FindControl("Qty")).Text;
OneDataRow["Price"] = Decimal.Parse(((TextBox)rRow.FindControl("Price")).Text,
NumberStyles.Currency);
}
}
So, the above takes ANY edit - any row you edit, and send changes from LV->rstData.
So, now we need the rstData save all rows, all edits, all additions back to the database, and that code is this:
void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Fighters", conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
}
}
}
So, now that is quite much all we need.
The last button, "add row" is also easy, and looks like this:
protected void cmdAddNew_ServerClick(object sender, EventArgs e)
{
// user might have done some editing, so, pull LV to table
// just in case
GridToTable();
// add new row to database
DataRow MyNewRow = rstData.NewRow();
// setup some defaults and values for this new row
//MyNewRow["DateCreate"] = DateTime.Now;
rstData.Rows.Add(MyNewRow);
ListView1.DataSource = rstData;
ListView1.DataBind();
}
That is it. So, if I am looking at above LV, and hit add-new, we now have this:
so I can just fill out the information, and then hit save. If I hit un-do, then the row will not be added (nor saved).
Note how we had a min of code to do the save. Note how we did not mess with a boatload of templates (and thus save world poverty).
So, this works really nice, was not a lot of code and the real secrets "idea" here was persisting the rstData. This allows great ease of adding new rows, but MORE important it was very simple then to send the edits back to the database, and that one save command will not only save any editing in the LV, but also will create the new rows in the database for you. So, you can quite much tab around in that lv - almost like excel. So we don't have a huge mess of "edit" buttons, and all that jazz. Just a simple grid of data, and a simple save, or add new button.
Note VERY careful how the GridToTable works. As this shows HOW to grab, and get values from the LV, and that was quite much the "major" part of your question. So, you can grab any row of the LV, but to pull values out of the one row, you have to use "FindControl".
protected void savetodatabase_Click(object sender, EventArgs e)
{
System.Web.UI.HtmlControls.HtmlGenericControl Labelid;
TextBox quantity2;
foreach (ListViewItem rRow in ListView1.Items)
{
itemlist iteml = new itemlist();
quantity2 = (TextBox)rRow.FindControl("quantity2");
Labelid = (System.Web.UI.HtmlControls.HtmlGenericControl)rRow.FindControl("Labelid");
iteml.quantity = quantity2.Text;
iteml.bookid = Convert.ToInt32(Labelid.InnerText) ;
iteml.Date = DateTime.Now;
iteml.userid = Convert.ToInt32(Session["userid"].ToString()) ;
DatabaseContext context = new DatabaseContext();
context.itemlists.Add(iteml);
context.SaveChanges();
}
}
I have 8 items in a SQL table with a Description, ItemNumber, and ImagePath.
protected void Page_Load(object sender, EventArgs e)
{
//fill the datalist for the Signs Table
string tCallFrom = "Program." + System.Reflection.MethodBase.GetCurrentMethod().Name;
string tQry = #"SELECT * FROM [js_Signs]";
DataTable tblSigns = objCommMethods.fReturnTableFromQry(clsDBSelect.enumDBSelect.ProjectMaster, tQry, tCallFrom);
SignsList.DataSource = tblSigns;
SignsList.DataBind();
}
I am using a DataList to show all of the items along with a textbox that will allow a user to input the number of items they want:
<asp:DataList ID="SignsList" runat="server" RepeatColumns="4" CellPadding="2" Width="90%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<table>
<tr>
<th>
<%#DataBinder.Eval(Container.DataItem, "Description") %>
</th>
</tr>
<tr>
<th>
<%#DataBinder.Eval(Container.DataItem, "ItemNumber") %>
</th>
</tr>
<tr>
<td>
<asp:Image ID="SignImage" runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem, "ImagePath") %>' />
</td>
</tr>
<tr style="text-align: center;">
<td>
<asp:TextBox ID="txtSignQuantity" runat="server" CssClass="txtBox" BackColor="White" Enabled="true"
type="number" min="0" ToolTip="Please choose quantity of signs needed."/>
</td>
</tr>
<tr>
<td>
<p> </p>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<div class="btnGroup">
<div class="btnDiv">
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btnSave" Width="90px" Visible="true" OnClick="btnSave_Click"/>
</div>
<div class="btnDiv">
<asp:Button ID="btnCancel" runat="server" Text="Clear" CssClass="btnCancel" Width="90px" Visible="true" OnClick="btnCancel_Click"/>
</div>
</div>
After the saved button is clicked in C# I want to find out the value that a user entered but it is always returning null:
protected void btnSave_Click(object sender, EventArgs e)
{
TextBox txtSignQuantity;
string tempSignQuantity;
try
{
foreach (DataListItem item in SignsList.Items)
{
txtSignQuantity = item.FindControl("txtSignQuantity") as TextBox;
tempSignQuantity = txtSignQuantity.Text;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
I also checked and the Count of SignsList.Items was 8, so I know that it is retrieving the correct information. Sorry, I've never used a Data List before so I'm not really sure how to go about this...
The short answer is that data binding on postback is causing the problem. Check the Page.IsPostBack property before doing data binding:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//fill the datalist for the Signs Table
string tCallFrom = "Program." + System.Reflection.MethodBase.GetCurrentMethod().Name;
string tQry = #"SELECT * FROM [js_Signs]";
DataTable tblSigns = objCommMethods.fReturnTableFromQry(clsDBSelect.enumDBSelect.ProjectMaster, tQry, tCallFrom);
SignsList.DataSource = tblSigns;
SignsList.DataBind();
}
}
ASP.NET WebForms attempts to abstract away the fact that the control instances that were used to render the page are not the same instances it has when handling postback events. Data binding compounds the abstraction because it has to create controls in response to the DataBind call, and then on postback, recreate them based on the ViewState it saved.
Initializing controls from ViewState happens on the Init event, so when the Load event is fired later in the page lifecycle and you call DataBind on the control, everything it restored gets wiped out and recreated.
As for why you were getting null, it may have been that the controls were wiped out but not recreated; it may have had to do with other event handlers that didn't get rewired after the second data binding.
Guys before asking this questions I did a lot of research on this topic but I am not able to detect the problem.I have radio button in the datalist and I am trying to get the selected radio button value.But it is showing me false for all radio button on submit button.My datalist is like this:
<asp:DataList ID="dlEmails" RepeatLayout="Flow" runat="server" >
<HeaderTemplate>
<table>
<tr>
<th>Select Email Address </th>
<th>Status</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:RadioButton ID="rbtnSelect" Text='<%#Eval("Emails") %>' onclick='fnrad(this);' GroupName="a" Checked='<%#Eval("Primary") %>' runat="server" /><br />
(<asp:Label ID="lablel" runat="server" Text='<%#Eval("Verified") %>'> </asp:Label>)
</td>
<td valign="middle">
<asp:Label ID="lblID" Style="display: none;" runat="server" Text='<%#Eval("Id") %>'> </asp:Label>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Main") %>'> </asp:Label>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
Javascript for allowing only single radio button selection at a time is like this:
<script>
function fnrad(rbtn) {
var radioList = document.getElementsByTagName("input");
for (var i = 0 ; i < radioList.length; i++) {
if (radioList[i].type == "radio") {
radioList[i].name = 'a';
radioList[i].checked = false;
}
}
rbtn.checked = true;
rbtn.setAttribute("Checked","checked");
}
</script>
And my code behind is like this:
public partial class Member_EmailList : System.Web.UI.Page
{
EmailsBAL _mbl = new EmailsBAL(SessionContext.SystemUser);
DataSet _ds = new DataSet();
URLMessage URLMessage = new URLMessage();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
_mbl.LoadByUser(_ds, 1);//SessionContext.SystemUser;
dlEmails.DataSource = _ds.Tables[_mbl.SqlEntityX];
dlEmails.DataBind();
}
protected void lnkConfirm_Click(object sender, EventArgs e)
{
RadioButton rb;
Label lbl;
int id = 0;
foreach (DataListItem di in dlEmails.Items)
{
rb = (RadioButton)di.FindControl("rbtnSelect");
if (rb.Checked == true)
{
lbl = (Label)di.FindControl("lblID");
id = WebHelper.Cast(lbl.Text, 0);
}
}
//Response.Redirect("~/Member/ConfirmEmail.aspx?" + URLMessage.Encrypt("SystemUser=" + SessionContext.SystemUser + "Id=" + id.ToString()));
}}
I tried your javascript function and experienced your problem
I would like to suggest to use Jquery on your javascript function. I refactored your jav fuction to this.
function fnrad(rbtn) {
$('input').removeAttr('checked');
$(rbtn).prop('checked', true);
}
This works perfectly on my end. Please let me know if you still encountering the issue.
I have a DropDownList inside in ListView..
I wanted to get a data when command clicked.
this is my code..
protected void ListView2_ItemCommand(object sender, ListViewCommandEventArgs e){
string shipmethod = ((DropDownList)e.Item.FindControl("ShippingComapnyDDL")).SelectedValue;
}
but it always return null value..
I've googling about 3 hours, and try many function..
but still cant solve this bug..
please help me guys,
UPDATE
here's my aspx page
<asp:DropDownList ID="ShippingComapnyDDL" runat="server" SelectedValue='<%# Eval("ShippingCompany") %>'>
<asp:ListItem Text="" Value=""></asp:ListItem>
<asp:ListItem Text="FedEx" Value="FedEx"></asp:ListItem>
<asp:ListItem Text="UPS" Value="UPS"></asp:ListItem>
<asp:ListItem Text="Other" Value="Other"></asp:ListItem>
</asp:DropDownList>
DO you have headers set?try
if(e.Item.ItemIndex!=-1)
{
string shipmethod = ((DropDownList)e.Item.FindControl("ShippingComapnyDDL")).SelectedValue;
}
if not working then try
string shipmethod = (e.Item.FindControl("ShippingComapnyDDL") as DropDownList).SelectedValue;
Please try
<%#DataBinder.Eval(Container.DataItem,"ShippingCompany")%>
instead of
<%#Eval("ShippingCompany")%>
For more details:
http://aspadvice.com/blogs/joteke/archive/2008/08/24/Is-_2200_Databinding-methods-such-as-Eval_280029002C00_-XPath_280029002C00_-and-Bind_28002900_-can-only-be-used-in-the-context-of-a-databound-control_2E002200_-causing-you-grief_3F00_.aspx
try this:
DropDownList ddl = (DropDownList)e.Item.FindControl("ShippingComapnyDDL");
if (ddl != null)
{
//code here
}
<asp:ListView ID="lvwCoreConfigureData" runat="server" DataKeyNames="Course_Config_Id" OnItemCommand="lvwCore_Config_ItemCommand" OnItemDataBound="lvwCore_Config_ItemDataBound">
<LayoutTemplate>
<table class="table mobile-stacked mb-0">
<thead>
<tr role="row">
<th style="width: 240px">
<asp:Label runat="server" Text="<%$Lang:Resource.Core_Config_Course %>"></asp:Label>
</th>
</tr>
</thead>
<tbody>
<tr runat="server" id="itemPlaceholder" />
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr role="row">
<td data-th="Name">
<asp:DropDownList ID="ConfigCourseName" runat="server" AutoPostBack="true" CssClass="form-control" OnSelectedIndexChanged="ConfigCourseName_SelectedIndexChanged"></asp:DropDownList>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
2 . This methos will be provide data binding to dropdown while edit mode
protected void lvwCore_Config_ItemDataBound(Object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item; // load one row item
var CourseId = ((Edulearn.Model.CoreProgramme.CoreProgrammeConfigrationDM)dataItem.DataItem).CourseId; //
DropDownList ConfigCourseName = (e.Item.FindControl("ConfigCourseName") as DropDownList);
ConfigCourseName.DataSource = CoreProgrammeRepository.GetCoreProgrammeCourseList(TimeZoneId, new { Name = "TEST" }); // Get the data to dropdown (all data)
ConfigCourseName.DataTextField = "Name"; // assign here which one need to display
ConfigCourseName.DataValueField = "CourseId"; // assign here which one is the value for database save
ConfigCourseName.DataBind(); // bind the data
ConfigCourseName.SelectedValue = CourseId.ToString(); // Here selected values from database will be added
ConfigCourseName.Items.Insert(0, new ListItem("Please select")); // Default value only for display
}
}
Thanks in advance for your help.
I am using c#.net.
I have two views on my webpage (contained within one multiview), both contain buttons.
view_1
Contains a repeater/datasource and an custom made ‘edit’ button (which holds the ID for each row returned).
view_2
Contain an ‘update’ form and a ‘update’ button. When the user presses the update button the information within the database for that particular row is updated.
The problem I believe lies with my ‘update’ button within view_2
Code behind (‘update’ button), I have an if statement:
protected void Page_Load(object sender, EventArgs e)
{
updateSuccessFailed.Visible = false;
if (!Page.IsPostBack)
{
_multiView1.ActiveViewIndex = 0;
}
}
protected void update_Click(object sender, EventArgs e)
{
var Id = Convert.ToInt32((ID.Value));
notYetUpdated.Visible = true;
updateSuccessFailed.Visible = false;
tblV updateV = new tblV();
updateV.vID = venueId;
updateV.vame = updateName.ToString();
updateV.vPostcode = updatePropPostcode.ToString();
if (vRepos.Update(updateV))
{
notYetUpdated.Visible = false;
updateSuccessFailed.Visible = true;
updateMessage.Text = "Updated.";
}
else
{
notYetUpdated.Visible = false;
updateSuccessFailed.Visible = true;
updateMessage.Text = "An error has occurred, please try again.";
}
}
_view2
<asp:View ID="_view2" runat="server">
<div style="text-align:center" runat="server" id="notYetUpdated">
<table border="0" cellspacing="1">
<tr>
<td style="text-align:left;">Name</td>
<td style="text-align:left;"><asp:TextBox ID="updateName" MaxLength="60" runat="server" /></td>
</tr>
<tr>
<td style="text-align:left;">Postcode</td>
<td style="text-align:left;"><asp:TextBox ID="updatePropPostcode" MaxLength="60" runat="server" /></td>
</tr>
</table><br />
<asp:Button ID="updateVCancel" Text="Cancel" runat="server" onclick="cancel_Click" CssClass="standardButton" />
<asp:Button ID="updateVConfirm" Text="Update" runat="server" onclick="update_Click" CssClass="standardButton" />
<asp:HiddenField ID="vUpdateID" runat="server" />
</div>
<div style="text-align:center" runat="server" id="updateSuccessFailed">
<p><asp:Label ID="updateMessage" runat="server" /></p>
<asp:Button ID="updateBack" Text="Back To Start" runat="server" onclick="backToStart_Click" CssClass="standardButton" />
</div>
</asp:View>
notYetUpdated / updateSuccessFailed are div’s which hold different information.
When the user first ‘updates’ a record it make the right div visible. (notYetUpdated – holds the form information / updateSuccessFailed – holds a message to state whether the record has been updated or not). However when you access the view_2 again it accesses the update_Click event and updateSuccessFailed is visible even though it shouldn’t be.
I thought I could clear all stored information within the viewstates with the code below, however this is not working.
ViewState.Clear();
ClearChildViewState();
Thanks
Clare :-)
The 4th line should be updateSuccessFailed.Visible = false;?
This was an error on my part. I adapted my code, here it is:
var Id = Convert.ToInt32((ID.Value));
tblV updateV = new tblV();
updateV.vID = venueId;
updateV.vame = updateName.ToString();
updateV.vPostcode = updatePropPostcode.ToString();
notYetUpdated.Visible = false;
updateSuccessFailed.Visible = true;
if (vRepos.Update(updateV))
{
updateMessage.Text = "Updated.";
}
else
{
updateMessage.Text = "An error has occurred, please try again.";
}
Hope this helps other people.