Multiview - View Clear State - c#

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.

Related

FindControl() always returns null from DataList Textbox

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.

ASP.NET passing a function return value from a modalpopupextender to the main form

I have looked at a number of solutions to my basic issue, but have not found any solution that I either understand or that would work.
I have a page that takes in two items of information, filename and a store. The user then clicks on a button to execute a function that will update a database and send back a resulting string that I want to display on a textbox on the main form.
However, when they press the button I call a modalpopupextender using an UpdatePanel panel. That gets a value into the modalpopup. If the user validates that the correct store is selected they click an 'okay' button which then call the dbprocessing function that returns a result. The page is small so I'll give the complete aspx and c# code.
The function doProcess() returns a List of values which I convert to String for display. I left the session variables in for that was my last attempt at trying to get this to work.
Where I am confused is that when the first button on the main form (Process) is clicked, there is a postback which obviously hits the page load before the button click. That is when I display the popup. Then when the user clicks on the button Okay, another postback is perform hitting page load before the button click and in that second button I originally tried to set the textbox on the main page because there is no other action after the second click, but no data displayed.
What is strange, if I repeat the process, when I click to display the popup, my data displays. This is not making sense.
This is the aspx page
<%# Page Title="Product Rank Loader" Language="C#" MasterPageFile="~/OMnested.master" AutoEventWireup="true" CodeBehind="ProductRankLoader.aspx.cs" Inherits="OrderManager.ProductRankLoader" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="Scripts/local.js"></script>
<script type="text/javascript">
function callme(thisone)
{
$("#ddlStores").prop('disabled', false);
}
</script>
<div>
<table style="width: 500px">
<tr>
<td>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:FileUpload ID="fulRanks" runat="server" Width="315px" />
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlStores" runat="server" Height="16px" Width="155px">
<asp:ListItem Value="0">Select Store</asp:ListItem>
<asp:ListItem Value="10101">Parkseed</asp:ListItem>
<asp:ListItem Value="10151">Wayside</asp:ListItem>
<asp:ListItem Value="10201">Jackson (JP)</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td style="height: 20px; padding-top: 15px; padding-bottom: 15px; padding-left: 20px;">
<asp:Button ID="btnProcess" runat="server" Text="Process" Width="89px" OnClick="btnProcess_Click" />
</td>
</tr>
<tr>
<td>
**<asp:TextBox ID="txtResults" runat="server" Height="200px" ReadOnly="True" TextMode="MultiLine"></asp:TextBox>**
</td>
</tr>
</table>
<asp:HiddenField ID="hdnFilename" runat="server" />
</div>
<asp:UpdatePanel id="updVerifyChoice" runat="server">
<ContentTemplate>
<div style="display: none;">
<asp:Button ID="btnDummy" UseSubmitBehavior="true" OnClientClick="ShowModalPopup" OnClick="btnDummy_Click" runat="server" />
<%--Dummy Button added to assign the target controlid of PopupExtender--%>
<asp:Button ID="btnDummyButton" UseSubmitBehavior="true" runat="server" Text="DummyButton" Style="display: none;" />
</div>
<asp:Panel ID="pnlVerifyRequestPopup" runat="server">
<div style="background: #fff; padding-left: 3px; border: 1px solid #989898; border-top: 1px solid #989898 !important;">
<table style="background-color: #F7F5F4; width: 300px;">
<tr>
<td><label>Verify Process Request</label></td>
<td style="text-align: right;">
<label class="lbl_3">
<asp:LinkButton ID="lBtnVerifyRequestClose" CssClass="lnkCloseheaderedit" Text="Cancel"
runat="server" OnClick="lBtnBillUpdPopClose_Click" /></label>
</td>
</tr>
<tr>
<td style="width: 150px;" colspan="2">
<asp:Label ID="lblWarn" runat="server" Text="" Font-Size="Medium" ForeColor="#CC3300"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" class="align_right">
<asp:Button ID="btnPopVerify" runat="server" CssClass="order_searchbtn" Text="Okay"
OnClick="btnPopVerify_Click" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnReturnData" runat="server" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender ID="extVerifyProcess" runat="server" BehaviorID="extndPopBillUpdBehId"
TargetControlID="btnDummyButton" PopupControlID="pnlVerifyRequestPopup" CancelControlID="lBtnVerifyRequestClose">
</ajax:ModalPopupExtender>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The field in question that should get the returned values from the function is called txtResults.
Here is the c# code (I cut out unneeded code)
namespace OrderManager
{
public partial class ProductRankLoader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var currentUser = Request.LogonUserIdentity.Name.Split('\\')[1];
// Session.Add("returnText", "");
var header = Master.FindControl("lblpageheading") as Label;
header.Text = "Product Rank Loader";
if (IsPostBack)
{
try
{
//if (Session["Verified"].ToString() != "")
//{
Session["returnText"] = doProcess();
if (Session["returnText"].ToString() != "")
{
txtResults.Text = Session["returnText"].ToString();
lblMessage.Text = "";
}
//}
}
catch { }
} else
{
Session.Add("returnText", "");
Session.Add("Verified", "");
}
}
protected void btnProcess_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
string filename = Path.GetFileName(fulRanks.FileName);
hdnFilename.Value = filename;
if (fulRanks.HasFile)
{
ddlStores.Enabled = true;
String fileExtension =
System.IO.Path.GetExtension(fulRanks.FileName).ToLower();
String[] allowedExtensions = { ".txt", ".log" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
fulRanks.SaveAs(#"c:\temp\" + filename);
}
}
}
if (!fileOK || ddlStores.SelectedIndex <= 0)
{
lblMessage.Text = "Either the file name is incorrect or a store has not been selected.";
return;
} else { }
lblWarn.Text = "You are going to update item Ranks for store <br />" + ddlStores.SelectedItem + ".<br /><br />Press 'Okay' to process";
Session.Add("Verified", "true");
extVerifyProcess.Show();
}
protected void lBtnBillUpdPopClose_Click(object sender, EventArgs e)
{
Session["Verified"] = "";
Session["returnText"] = "";
Response.Redirect("ProductRankLoader.aspx");
}
protected void btnPopVerify_Click(object sender, EventArgs e)
{
//Session["returnText"] = doProcess();
Session.Remove("returnText");
Session.Remove("Verified");
}
private string doProcess()
{
string tmpResults = "";
Int32 store = 0;
if (ddlStores.SelectedIndex > 0)
{
Int32.TryParse(ddlStores.SelectedValue.ToString(), out store);
string filename = hdnFilename.Value;
ProductRankLoaderDLL.ProductRankLoaderDLL newRanks = new ProductRankLoaderDLL.ProductRankLoaderDLL(xxx);
List<string> results = newRanks.ProcessRanks();
foreach (string result in results)
{
tmpResults += result + '\r';
}
// txtResults.Text = tmpResults;
lblMessage.Text = "";
}
else
{
lblMessage.Text = "";
}
return tmpResults;
}
protected void btnDummy_Click(object sender, EventArgs e)
{
}
}
}
If I don't misunderstand your request your problem is caused by the postbacks. I think you can handle better your logic with jquery. For example you can use jquery to close the popup without performing postback:
$('#lBtnVerifyRequestClose').click(function (event) {
event.preventDefault();
$('#pnlVerifyRequestPopup').dialog('close');
});
the event.preventDefault() ensure that postback are not executed.
If you need server logic to put data on your popup you can bind a jquery function to the dialog on open event and retrieve there data / perform your logic. In this way your form will be submitted to the server only once at the end of the process.

Dropdownlist resetting and not keeping value during postbacks

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:&nbsp</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: &nbsp</asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="txtGumrukKodu"></asp:TextBox>
</td>
<td>
<asp:Label runat="server" ID="lblGumrukAdi">Gümrük Adı: &nbsp</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.

How to show/hide a button from server side?

I'm new to ASP.NET and C#, I tried few things but did not worked. I have an .aspx page where I have three buttons, as shown in below code:
<body>
<form id="htmlForm" runat="server">
<telerik:RadScriptManager ID="rsm" AsyncPostBackTimeout="1800" runat="server" />
<telerik:RadAjaxPanel ID="rap" runat="server" LoadingPanelID="ralp">
<table>
<tr>
<td colspan="2">
Invoice Download
</td>
</tr>
<tr>
<td>
Invoice Start #
</td>
<td>
<telerik:RadNumericTextBox ID="rntbStart" Runat="server" MaxValue="1000000" MinValue="1000" Width="75px" >
<NumberFormat DecimalDigits="0" GroupSeparator="" />
</telerik:RadNumericTextBox>
</td>
</tr>
<tr>
<td>
Invoice End #
</td>
<td>
<telerik:RadNumericTextBox ID="rntbEnd" Runat="server" MaxValue="1000000" MinValue="1000" Width="75px" >
<NumberFormat DecimalDigits="0" GroupSeparator="" />
</telerik:RadNumericTextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="cmdDownload" runat="server" Text="Download" />
<asp:Button ID="cmdDownloadSAP" runat="server" Text="Download SAP" />
</td>
</tr>
</table>
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
</telerik:RadAjaxPanel>
<telerik:RadAjaxLoadingPanel ID="ralp" Runat="server" Skin="Default" />
<asp:Button ID="btnConform" Visible="false" runat="server" Text="Conform Download" OnClick="btnConform_Click" />
</form>
I'm trying to do that btnConform will be initially invisible while the page is loading and now if I click cmdDownload or cmdDownloadSAP, button btnConform must get visible. Now if I click again on btnConform it will become invisible.
I cannot use JavaScript because cmdDownload and cmdDownloadSAP have some other task to complete before I make btnConform visible (say database call) and the btnConform will become visible only if the database call is successful.
partial class XPO_Accounting_InvoiceDownload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdDownload_Click(object sender, System.EventArgs e)
{
Session["InvoiceStart"] = rntbStart.Value;
Session["InvoiceEnd"] = rntbEnd.Value;
try
{
//All DB call
btnConform.Visible = true;
}
catch (Exception ex)
{
lblResult.Text = ex.ToString();
}
}
protected void cmdDownload0_Click(object sender, System.EventArgs e)
{
Session["InvoiceStart"] = rntbStart.Value;
Session["InvoiceEnd"] = rntbEnd.Value;
try
{
//All DB call
btnConform.Visible = true;
}
catch (Exception ex)
{
lblResult.Text = ex.ToString();
}
}
override protected void OnInit(EventArgs e)
{
base.OnInit(e);
cmdDownload.Click += cmdDownload_Click;
cmdDownloadSAP.Click += cmdDownload0_Click;
}
protected void btnConform_Click(object sender, EventArgs e)
{
double InvoiceStart = (double)Session["InvoiceStart"];
double InvoiceEnd = (double)Session["InvoiceEnd"];
try
{
SqlHelper.ExecuteNonQuery(XPOStaticData.Instance.SQL, CommandType.Text, "update tblInvoiceNum set uploadedtoacct = 'Y' WHERE Status='I' AND InvoiceNum BETWEEN " + InvoiceStart + " AND " + InvoiceEnd + " and uploadedtoacct = 'N'");
lblResult.Text = "Downloaded Invoiced has conformed as the correct one.";
btnConform.Visible = false;
}
catch (Exception ex)
{
lblResult.Text = ex.ToString();
}
}
}
This does not work.
Sorry for change the content of the question (cause older content wasn't pointing the problem properly). This is actual code here I'm trying to do it. (it looks stupid to pest the complete code...)
Add the Visible property to the Button using markup to initially set the second button's visibility:
<asp:Button ID="btnOne" runat="server" Text="One" OnClick="btnOne_Click" />
<asp:Button ID="btnTwo" runat="server" Visible="False" Text="Two" OnClick="btnTwo_Click" />
And on the event handlers, add this:
protected void btnOne_Click(object sender, EventArgs e)
{
btnTwo.Visible = true;
}
protected void btnTwo_Click(object sender, EventArgs e)
{
btnTwo.Visible = false;
}
You change visibility with the Visible property:
protected void btnOne_Click(object sender, EventArgs e)
{
//require code to make it visible
btnTwo.Visible = true;
}
protected void btnTwo_Click(object sender, EventArgs e)
{
//require code to make it invisible
btnTwo.Visible = false;
}
If you want to make a server control initially invisible you also have to use this property, so you can either use codebehind to change visibility programmatically ore declaratively on the aspx-page:
<asp:Button ID="btnTwo" Visible="false" runat="server" Text="Two" OnClick="btnTwo_Click" />
One final note, Visible=false on serverside means that this control is not rendered at all on client-side. So it does simply not exist and can not be accessed (or made visible) on client-side.
If you need to access it on client-side you should make it invisible via stylesheets either by using
display: none(does not take up any space) or
visibility: hidden(still takes up space in the layout).
Update acc. to the last edit of your question the event handlers don't seem to be registered anymore.
So you need:
<asp:Button ID="cmdDownload" OnClick="cmdDownload_Click" runat="server" Text="Download" />
<asp:Button ID="cmdDownloadSAP" OnClick="cmdDownload0_Click" runat="server" Text="Download SAP" />

Checkboxlist inside a usercontrol going as null when control passed from an aspx page

Have landed into a scenario again. The summary is as follows:
I have a user-control which is basically a mix up of a textbox,imagebuttons,checkboxlist incorporated together to look like a single-select dropdown with checkboxes..works pretty fine. One of the images inside the usercontrol opens up an aspx page as a popup.have few functionalities there viz saving values to database and stuffs.
On the OK button click of the popup page, I should be able to save the values to the DB as well as populate the usercontrol(which acts as a dropdown) with the value which I have saved to the DB.
Here the problem arises, when trying to bind the checkboxlist(present in the usercontrol) to the values from the DB, I get the error that the checkboxlist object is null and has not been created.
I feel that on the OK button click, the usercontrol has to refresh and hence the checkboxlist will be active.
PFB the relevant codes:
Usercontrol.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="SingleSelectCustomDropDown.ascx.cs" Inherits="MS.IT.Informa.UI.UserControls.SingleSelectCustomDropDown" %>
<asp:Panel ID="panel" runat="server">
<div id="FirstDiv">
<table>
<tr>
<td align="right">
<asp:TextBox ID="txtSelect" runat="server" ReadOnly="true"></asp:TextBox>
</td>
<td>
<asp:Image ID="imgShow" ImageUrl="../Images/DDGlyph.png" onmouseover="this.src='../Images/DDGlyphHOVER.png'" onmouseout="this.src='../Images/DDGlyph.png'" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="SecondDiv" style="display:none;">
<asp:CheckBoxList ID="chkBoxList" runat="server">
<asp:ListItem Value="0" Text="Standard" Selected="True"></asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="ThirdDiv" style="display:none;">
<asp:ImageButton ID="btnNew" runat="server" Height="20px" ImageUrl="~/Images/new.png" Width="20px" OnClientClick="ShowPopup();" />
<asp:ImageButton ID="btnEdit" runat="server" Height="20px" ImageUrl="~/Images/edit.png" Width="20px" />
<asp:ImageButton ID="btnDefault" runat="server" Height="20px" ImageUrl="~/Images/default.png" Width="20px" />
<asp:ImageButton ID="btnDelete" runat="server" Height="20px" ImageUrl="~/Images/delete.png" Width="20px" />
</div>
</td>
</tr>
</table>
</div>
</asp:Panel>
<script type="text/javascript">
//Displays the divs containing checkboxlist and images
function ShowList() {
document.getElementById("SecondDiv").style.display = "block";
document.getElementById("ThirdDiv").style.display = "block";
}
//Hides the divs containing checkboxlist and images
function HideList() {
document.getElementById("SecondDiv").style.display = "none";
document.getElementById("ThirdDiv").style.display = "none";
}
//Displays the selected item from the checkboxlist into the textbox placed in the Custom Control
function DisplaySelectedItem(sender, txtBoxID) {
var x = document.getElementById(sender.id);
var chkBoxPrefix = sender.id + "_";
var selectedText;
for (i = 0; i < x.rows.length; i++) {
if(document.getElementById(chkBoxPrefix+i).checked)
{
selectedText = document.getElementById(chkBoxPrefix+i).parentNode.innerText;
}
}
document.getElementById(txtBoxID.id).value = selectedText;
}
//Ensures that only one item is selected from the checkboxlist
function SelectOnlyOneCheckBox(e) {
if (!e) e = window.event;
var sender = e.target || e.srcElement;
if (sender.nodeName != 'INPUT') {
return;
}
var checker = sender;
var chkBox = document.getElementById('<%= chkBoxList.ClientID %>');
var chks = chkBox.getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
if (chks[i] != checker)
chks[i].checked = false;
}
}
function ShowPopup() {
window.open("ViewColumnOptions.aspx", "ViewColumnOptions", "height=300,width=600,left=300,top=150");
}
</script>
The codebehind for the usercontrol as below:
public partial class SingleSelectCustomDropDown : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
chkBoxList.Attributes.Add("onclick", "SelectOnlyOneCheckBox(event);DisplaySelectedItem(this," + txtSelect.ClientID + ");HideList();");
txtSelect.Attributes.Add("onclick", "ShowList();");
imgShow.Attributes.Add("onclick", "ShowList();");
}
}
public void PopulateOtherViews()
{
SaveReportViewFilter<ReportFilterBase> newObj = new SaveReportViewFilter<ReportFilterBase>();
ViewColumnOptions vwobj = new ViewColumnOptions();
newObj.UserName = vwobj.Page.User.Identity.Name;
SaveReportView<ReportFilterBase> obj2 = new SaveReportView<ReportFilterBase>();
DataTable dt = obj2.GetSaveReportViewFromDataBase(newObj);
chkBoxList.DataSource = dt;//chkBoxList becomes null here..we have ample data in the datatable though
chkBoxList.DataTextField = dt.Columns[0].ToString();
chkBoxList.DataValueField = dt.Columns[0].ToString();
chkBoxList.DataBind();
}
}
The function PopulateOtherViews is called on the button click of the aspx page.
Below is the code:
protected void btnOK_Click(object sender, EventArgs e)
{
if (chkSaveView.Checked)
{
if (!string.IsNullOrEmpty(txtViewName.Text))
{
//some code here to save the view name from txtViewName to the DB
SingleSelectCustomDropDown obj22 = new SingleSelectCustomDropDown();
obj22.PopulateOtherViews();
Page.ClientScript.RegisterStartupScript(this.GetType(),"close","CloseWindow();",true);
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertEnterViewName", "alertMessage('Please enter the view name');", true);
}
}
}
Any help, suggestions, pointers will be greatly appreciated.
Regards
Anurag
In btnOK_Click you are creating a new instance of the user control and not attaching it to the page. My suggestion is:
1.Register the user control and add it to the page.
<%# Register Src="~/UserControl/SingleSelectCustomDropDown.ascx" TagPrefix="uc1" TagName="SingleSelectCustomDropDown" %>
and ...
<uc1:SingleSelectCustomDropDown runat="server" id="obj22" />
2.Now modify in code behind:
protected void btnOK_Click(object sender, EventArgs e)
{
if (chkSaveView.Checked)
{
if (!string.IsNullOrEmpty(txtViewName.Text))
{
//some code here to save the view name from txtViewName to the DB
//Do not create the control again
//SingleSelectCustomDropDown obj22 = new SingleSelectCustomDropDown();
obj22.PopulateOtherViews();
Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "CloseWindow();", true);
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertEnterViewName", "alertMessage('Please enter the view name');", true);
}
}
}

Categories