I'm Having an Issue with Panels c# - c#

I have two pages:
Drop Down List that User picks a Customer Name from and a load button (Panel 1)
Page with Customer Order Information (Panel 2)
On the 2nd page, I have a check box that will show Customer Details in a DetailsView if it is checked.
My issue is when I go to click on the check box, it brings me back to my First Page with the DownDrop List, which is Panel 1. I have to click the load button to see the second panel again and once it's clicked again, it shows the DetailsView which the check box checked.
I have tried everything, this is what my code looks like:
protected void Page_Load(object sender, EventArgs e)
{
// always show first panel when page loads
pnlFirstPage.Visible = true;
pnlSecondPage.Visible = false;
}
protected void btnLoadOrders_Click(object sender, EventArgs e)
{
// hide the first page and continue to second page
pnlSecondPage.Visible = true;
pnlFirstPage.Visible = false;
// if statement to show details view of customer details
if (cbCustomerDetails.Checked == true)
{
dvCustomerDetails.Visible = true;
dvCustomerDetails.DataBind();
pnlFirstPage.Visible = false;
pnlSecondPage.Visible = true;
}

Ok, so the issue/problem is that keep in mind that EVERY post-back will trigger the page load event.
In other words, any button any dropdown/combo box, or ANY code event that triggers a post-back will fire the page load even EACH time, and THEN your button/event code stub runs.
Thus, for really what amounts to the last 200+ web form pages I built?
EVERY page for setup/loading controls, data etc. will have a if not postback code stub on the page load command.
So, say this markup in panel1
<asp:Panel ID="Panel1" runat="server">
<h3>Select Hotel</h3>
<asp:DropDownList ID="cboHotels" runat="server"
DataValueField="ID"
DataTextField="HotelName" Width="198px">
</asp:DropDownList>
<button runat="server" id="btnRun" title="Search"
style="margin-left: 15px"
type="button" class="btn"
onserverclick="btnRun_ServerClick">
<span class="glyphicon glyphicon-home"></span>View
<br />
</button>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" >
<h3>Hotel Infomration</h3>
<div id="EditRecord" runat="server"
style="float:left;display: normal;border:solid 2px;padding:12px;border-radius:12px">
<h2>Edit Hotel</h2>
<div style="float:left" class="iForm">
<label>HotelName</label>
<asp:TextBox ID="txtHotel" runat="server" f="HOtelName" width="280" /> <br />
bla bla bla for panel2.
so, now my code on startup can be to load up the combo box/dropdown list, and set Panel 1 visible, and panel 2 visible = false.
We have this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Panel1.Visible = true;
Panel2.Visible = false;
LoadData(); // load our combo box
}
}
void LoadData()
{
SqlCommand cmdSQL =
new SqlCommand("SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName");
cboHotels.DataSource = MyRstP(cmdSQL);
cboHotels.DataBind();
cboHotels.Items.Insert(0, new ListItem("Select", ""));
}
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And the button to view the details (in panel2), then can look like this:
protected void btnRun_ServerClick(object sender, EventArgs e)
{
if (cboHotels.SelectedIndex > 0)
{
string strSQL = "SELECT * FROM tblHotelsA WHERE ID = #ID";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = cboHotels.SelectedItem.Value;
DataTable rstData = MyRstP(cmdSQL);
General.FLoader(EditRecord, rstData.Rows[0]);
Panel1.Visible = false;
Panel2.Visible = true;
}
}
And now the results are this:
So, just keep in mind that the REAL first page load has to be inside of that if !IsPostBack stub.
You can think of that code stub the REAL or "first" page load. Thus, loading up a gridview, loading up a combo box, and say setting panel1 visible, and panel2 hidden all typical code that one would place in the real page startup code.
It quite much means you can't really build a working page without taking into account that page-load fires each and every time a event occurs on the page.
In fact, if you adopt a up-date panel, then the above will holds true.

Related

How to put a label into a checkboxlist from another page for asp.net

I tried doing this on the check box list page:
protected void Page_Load(object sender, EventArgs e)
{
(string)Session["name"] = cbl1.Items.Add;
}
but I don't know how to make it work.
You don't really "put a label into" a check box list from another page.
You might say have a check box list on one page, and you want to pass the selection(s) made in the first page, and pass to the 2nd page.
So, say we have a simple check box list of options on page 1
And a button to jump to the next page.
This markup:
<h3>Hotel Options</h3>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataValueField ="ID"
DataTextField="HotelOption" >
</asp:CheckBoxList>
<br />
<br />
<asp:Button ID="Button1" runat="server"
Text="Continue to next page" CssClass="btn" OnClick="Button1_Click" />
And code to load this up:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCheckBox();
}
void LoadCheckBox()
{
DataTable rstOptions =
MyRst("SELECT ID, HotelOption FROM tblOptions ORDER BY ID");
CheckBoxList1.DataSource = rstOptions;
CheckBoxList1.DataBind();
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Hotels))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And we now have this:
Ok, so now our code for the button.
We will get + save the above selections, and pass to the next page:
protected void Button1_Click(object sender, EventArgs e)
{
Session["MyItems"] = CheckBoxList1.Items;
Response.Redirect("WebForm2.aspx");
}
Ok, now our markup for the 2nd page.
We have this:
<h3>Hotel Options - on next page</h3>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataValueField ="Value"
DataTextField="Text" >
</asp:CheckBoxList>
<br />
Now, we saved the "items list" for the Check box list. The item list has a text and value property (we LOSE the colum name information that the data sourced used was).
So, note how the DataValueField="value" and DataTextField="Text" now.
So, this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCheckBox();
}
void LoadCheckBox()
{
ListItemCollection MyItems = (ListItemCollection)Session["MyItems"];
foreach (ListItem OneItem in MyItems)
{
CheckBoxList1.Items.Add(OneItem);
}
}
And now on 2nd page we have this:
Now it is NOT clear why I can't just bind this passed list directly to the check box list, but I found a foreach loop is required.
Now, it is perhaps not clear, but maybe you ONLY wanted the label text ones selected.
You can do this with this code:
ListItemCollection MyItems = (ListItemCollection)Session["MyItems"];
foreach(ListItem OneItem in MyItems)
{
if (OneItem.Selected)
{
Debug.Print("Label text = " + OneItem.Text);
Debug.Print("Check box value = " + OneItem.Value);
}
}
Output:
Label text = Smoking
Check box value = 1
Label text = Balcony
Check box value = 2
So, keep in mind that a check box list can often have 2 columns of data.
The display "label" or text, or the hidden value.
In my example, the "ID" is the PK value from the database, and I need that.
If you only have one "text" value, and don't care about a hidden database PK value, then often I just set both DataTextField and DataValueField to the SAME column in the database.
And if you using looping, and adding a listitem in code? Then the settings are not the field columns anymore, but Text and Value. You thus still have the ability to have 2 values - the display text, and some key or number value for a checkbox list.
Now perhaps you have two web pages open, and you want to change/set controls in the other web page?
No, you can't do that. Other web pages might say be open to someone's banking web site. You can't mess around with other web pages the user has open, since that would be a MASSIVE security hole, and no one would risk using the world wide web then, right?
Edit: placing the results on a label on the 2nd page
Ok, so the debug.print? That is just a handy debugging way of displaying some code values - only for developers. It really much like using console.log to display value(s) into the console. It certainly not for putting some text into a label (I realy thought that would be crystail clear to you - at a loss as to why you think debug.print has anything of value or is relavent to YOU writing code to put a few text values into a label).
So, ok, on the 2nd page we will have a label and not some check box list.
So, our markup on the 2nd page will now look like this:
<asp:Label ID="Label1" runat="server" Text=""
Font-Bold="true"
Font-Size="Large"
></asp:Label>
And in our page load event, we will have this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadLabel();
}
void LoadLabel()
{
ListItemCollection MyChoices = (ListItemCollection)Session["MyItems"];
// process selection list from
// previous page - shove reuslts into label
string strChoices = "";
foreach (ListItem OneChoice in MyChoices)
{
if (OneChoice.Selected)
{
if (strChoices != "")
strChoices += ",";
strChoices += OneChoice.Text;
}
Label1.Text = strChoices;
}
}
So, now on first page, we say select this:
And now on 2nd page, we see this:
Of course, we could change our code to display each choice on a new line,
Say this code:
void LoadLabel()
{
ListItemCollection MyChoices = (ListItemCollection)Session["MyItems"];
// process selection list from
// previous page - shove reuslts into label
string strChoices = "";
foreach (ListItem OneChoice in MyChoices)
{
if (OneChoice.Selected)
{
if (strChoices != "")
strChoices += #"<br/>"; // <-- new line in label
strChoices += OneChoice.Text;
}
Label1.Text = strChoices;
}
}
And now we would see this:
So, you can shove results into that label - separated by ",", or whatever.
Or, you can display the choices on a new line as per last example.

Cannot access control inside DetailsView Edit template

Hello everybody and thanks in advance,
Well, I have a DetailsView in my .aspx file and I can't access to a CheckBoxList control placed in the DetailsView's edit template. I've read a lot of threads about this but still can't find a solution. Here's the code...
<asp:DetailsView ID="MyDetailsView" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataSourceID="DataMyDetailsView">
...
...
<asp:TemplateField HeaderText="DATA" SortExpression="DATA">
<EditItemTemplate>
<div style="width:400px; height:300px; overflow-y:auto">
<asp:CheckBoxList ID="DataCL" runat="server" DataSourceID="DataEDIT" DataTextField="DATA" DataValueField="ID_DATA">
</asp:CheckBoxList>
</div>
Then, in my .cs file I have this piece of code...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Do something
}
else
{
CheckItems();
}
}
...
...
public void CheckItems()
{
CheckBoxList DataCL = (CheckBoxList)MyDetailsView.FindControl("DataCL");
using (conexion)
{
conexion.Open();
cmd.Connection = conexion;
DataSet ds = new DataSet();
string cmdstr = "SELECT * FROM DATA";
SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conexion);
adp.Fill(ds);
DataCL.DataSource = ds;
DataCL.DataTextField = "DATA";
DataCL.DataValueField = "ID_DATA";
DataCL.DataBind();
The problem is that when the execution reaches the first line in which the control is called (DataCL.DataSource = ds;), a "NullPointerExeception" is thrown, however I can access easily to controls in ItemTemplate.
Please, can someone help me in this. Thanks again!
You can't do this, because this control is dynamically created after data binding. Instead attach your grid to DataBound (MSDN) event and bind checked box list there
protected void MyDetailsView_DataBound(object sender, EventArgs e)
{
if (MyDetailsView.CurrentMode == DetailsViewMode.Edit)
{
CheckBoxList DataCL = (CheckBoxList)MyDetailsView.FindControl("DataCL");
using (conexion)
{
// your data bound code goes here
}
}
}

ASP.NET Session State & Postback problems

I have a problem that I believe is a session state issue, but I'm at a loss to figure out what's wrong. I have a sample project to illustrate the problem. (Code below) I have 2 buttons. Each populates a List with some unique data and then uses that data to add a row to a table. The row contains text boxes so that the user can edit the data. (For my sample, there's no update button to persist the data.) To reproduce the problem in VS2010, create a new "ASP.NET Web Application" project and copy/paste the aspx code and the c# code-behind into Default.aspx, then run the application.
Press the DataSet 1 button and the grid should populate with 1 row.
Edit the data in one of the text boxes and tab off of the text box. (The newly entered text should remian, and the font should be blue. This is what I want to happen.)
Now click either of the DataSet buttons to reset the List and refresh the table.
Edit the data in one of the text boxes and tab off the text box. (Immediately, the text in the box refreshes back to its original value. This only happens once, though. If you edit either text box now, it will work normally.)
This is repeatable... the first edit after pressing the DataSet buttons a 2nd, 3rd, etc. time gets reset back to the original value. And I can't figure out why.
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DebugPostbackIssue._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
Populate the table with DataSet #1:<asp:Button runat="server" ID="btnDS1" Text="Dataset 1" OnClick="btnDS1_Click" />
</p>
<p>
Populate the table with DataSet #2:<asp:Button runat="server" ID="btnDS2" Text="Dataset 2" OnClick="btnDS2_Click" />
</p>
<p>
<asp:Table runat="server" ID="tblData">
<asp:TableHeaderRow runat="server" ID="thrData">
<asp:TableHeaderCell Scope="Column" Text="Column 1"></asp:TableHeaderCell>
<asp:TableHeaderCell Scope="Column" Text="Column 2"></asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
</p>
</asp:Content>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DebugPostbackIssue
{
public partial class _Default : System.Web.UI.Page
{
private List<string> _MyData = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
LoadSessionData();
GenerateGrid(false);
}
protected void btnDS1_Click(object sender, EventArgs e)
{
_MyData = new List<string>();
_MyData.Add("111");
_MyData.Add("aaa");
SaveSessionData();
GenerateGrid(true);
}
protected void btnDS2_Click(object sender, EventArgs e)
{
_MyData = new List<string>();
_MyData.Add("222");
_MyData.Add("bbb");
SaveSessionData();
GenerateGrid(true);
}
private void SaveSessionData()
{
Session["MyData"] = _MyData;
}
private void LoadSessionData()
{
if (Session["MyData"] != null)
_MyData = (List<string>)Session["MyData"];
else
_MyData = new List<string>();
}
private void GenerateGrid(bool ClearData)
{
if (ClearData)
while (tblData.Rows.Count > 1)
tblData.Rows.Remove(tblData.Rows[tblData.Rows.Count - 1]);
TableRow tr = new TableRow();
foreach (string s in _MyData)
{
TableCell tc = new TableCell();
TextBox txtBox = new TextBox();
txtBox.Text = s;
txtBox.Attributes.Add("OriginalValue", s);
txtBox.TextChanged += new EventHandler(txtBox_TextChanged);
txtBox.AutoPostBack = true;
tc.Controls.Add(txtBox);
tr.Cells.Add(tc);
}
if (tr.Cells.Count > 0)
tblData.Rows.Add(tr);
}
void txtBox_TextChanged(object sender, EventArgs e)
{
TextBox Sender = (TextBox)sender;
if (Sender.Text == Sender.Attributes["OriginalValue"])
Sender.ForeColor = System.Drawing.Color.Black;
else
Sender.ForeColor = System.Drawing.Color.Blue;
}
}
}
Hi I took some time off of my work to compile your code, and I figured it out, just change your textbox change to the following :
void txtBox_TextChanged(object sender, EventArgs e)
{
TextBox Sender = (TextBox)sender;
if (Sender.Text == Sender.Attributes["OriginalValue"])
Sender.ForeColor = System.Drawing.Color.Black;
else
{
Sender.ForeColor = System.Drawing.Color.Blue;
if (Session["MyData"] != null)
{
List<string> _ss = (List<string>)Session["MyData"];
//_ss.Find(a => a == Sender.Attributes["OriginalValue"]);
_ss.Remove(Sender.Attributes["OriginalValue"]);
_ss.Add(Sender.Text);
}
}
}
ur welcome!
Try creating a datatable. I would, on "event" copy your asp table content to a datatable, then when you get the servers response add that to the datatable. Then copy the datatable back to your asp table, and repeat... Datatables can be used like variables.
Or try using a cookie.
Try changing...
protected void Page_Init(object sender, EventArgs e)
{
LoadSessionData();
GenerateGrid(false);
}
To...
protected override void OnLoadComplete(EventArgs e)
{
LoadSessionData();
GenerateGrid(false);
}
Based on your description I believe that your value is getting reset because of how the page life cycle works in ASP.NET & that is the page_init is getting called before your event due to ASP.NET quirkiness. Above code is how I work around it, I'm sure there's other ways too.
Okay, I have it working, now. Wizpert's answer pointed me in the right direction... Upon discovering that the TextChanged event did not fire during the times when the value was erroneously being reset to the original value, it occurred to me that during the Click events I was calling GenerateGrid(true). This forced the removal of the existing rows and the addition of new rows. (Removing & adding the dynamic controls at that point in the life cycle must be interfering with the TextChange event handler.) Since the Click event fires after Page Init and after Page Load, the state values were already written to the text boxes and I was overwriting them. But the 2nd text box edit did not force GenerateGrid(true) to be called so the state values were not overwritten any more.
If this sounds confusing, I apologize. I'm still wrapping my head around this. But suffice to say that I had to change my GenerateGrid method to reuse any existing rows and not delete them. (If they don't exist, like when GenerateGrid is called from Page Init, then they are added.) So this was a page lifecycle issue after all.
Thank you.

ASP.net C# Bind Gridview using a button inside modalpopup

Codes of the button inside modalpopup (
protected void btnYes_Click(object sender, EventArgs e)
{
int index = Convert.ToInt32(gvItemAssignment.SelectedRow.Cells[1].Text);
con.Close();
con.Open();
SqlCommand delete = new SqlCommand("UPDATE tblAssignment SET AssignDeleteStatus = 'Deleted' WHERE AssignID = " + index + "", con);
delete.ExecuteNonQuery();
con.Close();
dgvItemAssignment.DataBind();
btnDelete_ModalPopupExtender.Hide();
}
Modalpopup
<asp:ModalPopupExtender ID="btnDelete_ModalPopupExtender" runat="server"
BackgroundCssClass="modalBackground" CancelControlID="btnNo"
PopupControlID="Panel3" TargetControlID="btnRemove">
</asp:ModalPopupExtender>
btnRemove for calling (no codes inside)
Main problem is the Databind on btnYes is not working. Gridview is outside. ill click remove button then the popup shows. Then click btnYes inside, doing all the codes except databind, then popup hides. Tried doing this.Databind(); and also IsPostback on the PageLoad. Very much appreciated if you could help me with this. Stuck in a while.

Not able to display content in <EditItemTemplate> in FormView

What am I doing wrong since the content in the < EditItemTemplate > is not displayed when I click the Edit button?
<asp:FormView runat="server" id="fwHotelDetails" DataKeyNames="id" OnDataBound="fwHotelDetails_DataBound" OnModeChanging="fwHotelDetails_ModeChanging">
<ItemTemplate>
//display content here
<asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />
</ItemTemplate>
<EditItemTemplate>
This text should be displayed when I click the Edit button
<asp:LinkButton runat="server" ID="UpDateButton" CausesValidation="false" CommandName="Update" Text="Lagre" />
</EditItemTemplate>
</asp:FormView>
Update
This is my code-behind:
namespace development.templates
{
public partial class HotelDetails : TemplatePage
{
static Hotel hotel;
protected DataRow drHotel;
DataTable dtCriteria;
DataTable dtHotel;
private HotelCriteria hotelCriteria;
protected void Page_Load(object sender, EventArgs e)
{
int hotelID = Convert.ToInt32(Request.QueryString["hotelid"].ToString());
if (!IsPostBack)
{
if (hotelID != 0)
{
// Create Hotel instance based on hoteID.
hotel = new Hotel(hotelID);
drHotel = hotel.hotelData.Rows[0];
dtHotel = hotel.getHotelsByCity(drHotel["city"].ToString());
// Hotel scrore is calculated from a score which is derived from certain criterias.
hotelCriteria = new HotelCriteria(hotelID);
dtCriteria = hotelCriteria.getHotelCriteria();
//Set datasource for hotel list in right sidebar.
hotelListByCity.DataSource = correctList(dtHotel, hotelID);
hotelListByCity.DataBind();
// Set datasource for current hotel
fwHotelDetails.DataSource = hotel.hotelData;
fwHotelDetails.DataBind();
}
}
}
protected void fwHotelDetails_DataBound(object sender, EventArgs e)
{
//Find the criteria list and set the datasource
Repeater rep = (Repeater)fwHotelDetails.FindControl("repCriteriaScore");
rep.DataSource = this.dtCriteria;
rep.DataBind();
// Controll is user is logged in. If logged in, then user may add, edit or delete hotel record.
System.Security.Principal.IPrincipal user = Context.User;
if ((user != null) && user.Identity.IsAuthenticated){
Panel panel = (Panel)fwHotelDetails.FindControl("administrationPanel");
panel.Visible = true;
}
}
protected void fwHotelDetails_ModeChanging(object sender, FormViewModeEventArgs e)
{
switch (e.NewMode)
{
case FormViewMode.Edit:
MessageLabel.Text = "Edit mode";
fwHotelDetails.ChangeMode(FormViewMode.Edit);
break;
case FormViewMode.ReadOnly:
MessageLabel.Text = "Read mode";
break;
case FormViewMode.Insert:
MessageLabel.Text = "Insert mode";
break;
}
}
}
}
The EditItemTemplate also won't show up if the record is empty. In other words, if you have a gridview that you select a detail record from that is feeding the formview, and their is no detail for the selected grid item, then the form won't show up at all. I check to see if the detail record is null, and if so, I set the formview or detailsview to "insert" mode. so they can enter a new record.
In your function fwHotelDetails_ModeChanging, add this:
fwHotelDetails.ChangeMode(FormViewMode.Edit)
i.e.
Protected Sub fwHotelDetails_ModeChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewModeEventArgs) Handles fwHotelDetails.ModeChanging
fwHotelDetails.ChangeMode(FormViewMode.Edit)
End Sub
Ok have you tried putting a breakpoint on fwHotelDetails_ModeChanging and then debugging the App? Does the breakpoint get hit when you click the edit button.
At least this will tell you where your problem lies. That is [1] the events are not hooked up correctly or [2] there is something going wrong with ChangeMode.
I realise this isnt a solution but if you tell me whether the breakpoint hits i can help you further.

Categories