Remove whitespace after disabled control in asp.net - c#

I have small page, it looks follows:
Some header
Label with text only for logged users
Hyperlink
Logout button
Here is the behind code:
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.Name == "")
{
Label1.Visible = false;
Controls.Remove(Label1);
}
else
{
Label1.Visible = true;
}
}
Question is: When non logged user loads page, the label is not shown. But how to move the hyperlink and logOutButton and thus hide the white space on place, where the label is invisible ?
Thanks

You have to use the css display:none here

You have to create an Authentication Panel it's a asp:Panel extended and it will able you control "Logged and non Logged user without any headache".
example:
public class AuthenticatedPanel : Panel
{
public string Action { get; set; }
public AuthenticatedPanel()
{
this.Load += new EventHandler(AuthenticatedPanel_Load);
}
void AuthenticatedPanel_Load(object sender, EventArgs e)
{
//your logic to check wether is user is legit or not
// and then
this.Visible = false;
}
}
//then using
<asp:AuthenticatedPanel ID="pnl" runat="server">
your content here
</asp:AuthenticatedPanel>

In summary, per the information above and some research, here's what worked for me. The white space IS removed by using button.Visible = false in codebehind but the "br" tags are remaining, so wrap them inside individual panels and hide the panel, not the button, i.e. panel.Visible = false and it will remove all the white space.

Here's an example, on the .aspx page, create a panel with a control inside(notice the "br" tag inside it):
<asp:Panel ID="panel" runat="server">
<asp:Button ID="button" runat="server"/>
<br />
</asp:Panel>
next, on codeBehind, hide the panel instead of the button:
panel.Visible = false;

Related

Open an aspx page as a modal popup on button click from another aspx page

I have two web pages Home.aspx and Details.aspx.
In Home.aspx, I have a table with few contents and one of the column is a link button. On this button click, I'm directing the page to Details.aspx using Response.Redirect("Details.aspx") and also passing some values using commandArgument
<td><asp:LinkButton ID="LinkButton1"
runat="server"
Text='<% # Eval("Count") %>'
CausesValidation="false"
commandArgument='<%#Eval("title")+","+ Eval("Count") %>'
OnCommand="LinkButton1_Click"/>
</td>
protected void LinkButton1_Click(object sender, CommandEventArgs e)
{
string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
string title = commandArgs[0];
Session["title"] = title;
string count= commandArgs[1];
Response.Redirect(string.Format("Details.aspx?title={0}&count={1}", title, count), false);
}
In Details.aspx, on page load, with these session details, im performing some operation which gives me a list of values and using these values im generating a repeater.
Details.aspx page:
protected void Page_Load(object sender, EventArgs e)
{
string conTitle = (string) Session["title"];
List <string> myTitleList = (List<string>) Session["docTitles"];
List<List<string>> myTitleContentList = (List<List<string>>)Session["content"];
int i = myTitleList.IndexOf(conTitle);
try
{
List<string> displayList = myTitleContentList[i];
cdcatalog.DataSource = displayList;
cdcatalog.DataBind();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
Now I want to do all this on a modal popup instead of Response.Redirect.
Is it possible to load an aspx page as a modal popup on button click.
You can use ModalPopUp from Ajax Control Toolkit
The ModalPopup extender allows a page to display content to the user
in a "modal" manner which prevents the user from interacting with the
rest of the page. The modal content can be any hierarchy of controls
and is displayed above a background that can have a custom style
applied to it.
You can use place the content in a div and open the Pop-Up using Jquery.
Use a modal dialog to require that the user enter data during a
multi-step process. Embed form markup in the content area, set the
modal option to true, and specify primary and secondary user actions
with the buttons option.

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.

Unselect radio button list on click

I need to unselect radio button in radio button list, i know it is more sensible to use checkbox but the management wants radio button to be unchecked.
RadioButtonList control is a collection of ListItems. To clear one radio button in the control you need to use Index for that particular item. To clear all radio buttons in the control, there is a method "ClearSelection()".
//To Unselect First Item
RadioButtonList1.Items[0].Selected = false;
//To unselect all Items
RadioButtonList1.ClearSelection();
hope this will resolve your issue.
private void Clear()
{
if(RadioButton1.Checked)
{
RadioButton1.Checked = false;
}
}
Use this:
RadioButton1.Checked = false;
myRadioButtonList.SelectedIndex = -1;
Hope this help.
You mean you want it to be possible for your radio button group to have zero values selected? Technically, you can just ensure that no radio in the group has its checked value set. checked="" or just delete the entire attribute.
Be aware that this is an invalid state for the radio group. It's like a boolean that is set to neither true nor false. It makes no sense semantically and is in violation of the HTML spec.
If you are constrained to a radio group, the only valid option is to include one radio that represents a 'none of the other options' state.
I had the same problem. In my case, I was using the radio button checkedChanged event to automatically append a medical documentation string snippet into a rich text box control. The snippet would be different for each radio button selected, and the requirement was that only one choice could be allowed. So radio buttons were the best choice instead of check boxes. The problem was that if the user wanted to remove ALL of the text snippets from the textbox, the s/he could just manually select the text from the box and delete it -- but at least one radio button would remain selected.
So, I found that the easiest way to fix this would be to add a button to the form and use its _Click event to set the specified radio button checked status to false.
So, My code looked like this...
// for rad 1
private void rad_NoDifferent_CheckedChanged(object sender, EventArgs e) {
if(rad_NoDifferent.Checked) {
rtb_GSC_Notes.AppendText(sRating_NoDiffMsg);
} else {
rtb_GSC_Notes.Text = rtb_GSC_Notes.Text.Replace(sRating_NoDiffMsg, sNoMsg.TrimEnd());
}
}
// for rad 2
private void rad_VeryDifferent_CheckedChanged(object sender, EventArgs e) {
if(rad_VeryDifferent.Checked) {
rtb_GSC_Notes.AppendText(sRating_VeryDiffMsg);
} else {
rtb_GSC_Notes.Text = rtb_GSC_Notes.Text.Replace(sRating_VeryDiffMsg, sNoMsg.TrimEnd());
}
}
// for rad 3
private void rad_Unsure_CheckedChanged(object sender, EventArgs e) {
if(rad_Unsure.Checked) {
rtb_GSC_Notes.AppendText(sRating_UnsureMsg);
} else {
rtb_GSC_Notes.Text = rtb_GSC_Notes.Text.Replace(sRating_UnsureMsg, sNoMsg.TrimEnd());
}
}
// for button reset
private void btn_ClearRadioButtons_Click(object sender, EventArgs e) {
rad_NoDifferent.Checked = false;
rad_Unsure.Checked = false;
rad_VeryDifferent.Checked = false;
}
Recently I was facing same issue however I found the solution with Radio button.
below are the aspx code for radio button
<div>
<asp:RadioButton ID="RadioButton1" GroupName="myg" onClick="clicked(this.id);" runat="server" />
<asp:RadioButton ID="RadioButton2" GroupName="myg" onClick="clicked(this.id);" runat="server" />
<asp:RadioButton ID="RadioButton3" GroupName="myg" onClick="clicked(this.id);" runat="server" />
<asp:RadioButton ID="RadioButton4" GroupName="myg" onClick="clicked(this.id);" runat="server" />
</div>
Just write below java script.
<script type="type/javascript">
var arr = [];
function clicked(radid) {
var ra = document.getElementById(radid);
if (arr.indexOf(radid) < 0) {
arr.splice(0, arr.length);
arr.push(radid);
}
else {
arr.splice(0, arr.length);
ra.checked = false;
}
}
</script>
Hope this will solve your purpose.
WPF/C#
if (RadioBTN.IsChecked == true) {
RadioBTN.IsChecked = false;
}

asp.net c# is checkbox checked?

How do I determine if the checkbox is checked or not checked?
Very perplexed why this is not working - it is so simple!
On my web form:
<asp:CheckBox ID="DraftCheckBox" runat="server" Text="Save as Draft?" />
<asp:Button ID="PublishButton" runat="server" Text="Save" CssClass="publish" />
Code behind which runs in the click event for my save button:
void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
}
When debugging it never steps into the If statement when I have the checkbox checked in the browser. Ideas?!
I think there maybe some other code affecting this as follows...
In Page_load I have the following:
PublishButton.Click += new EventHandler(PublishButton_Click);
if (newsItem.IsDraft == 1)
{
DraftCheckBox.Checked = true;
}
else
{
DraftCheckBox.Checked = false;
}
newsItem is my data object and I need to set the checkbox checked status accordingly.
When the save button is hit I need to update the IsDraft property based on the checked status of the checkbox:
void PublishButton_Click(object sender, EventArgs e)
{
if (IsValid)
{
newsItem.Title = TitleTextBox.Text.Trim();
newsItem.Content = ContentTextBox.Text.Trim();
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
else
{
newsItem.IsDraft = 0;
}
dataContext.SubmitChanges();
}
}
So, isDraft = 1 should equal checkbox checked, otherwise checkbox should be un-checked. Currently, it is not showing this.
Specify event for Button Click
<asp:Button ID="PublishButton" runat="server" Text="Save" onclick="PublishButton_Click" />
What i can see you have not got a OnClick on your button. So like this:
<asp:CheckBox ID="DraftCheckBox" runat="server" Text="Save as Draft?" />
<asp:Button ID="PublishButton" runat="server" OnClick="PublishButton_Click"
Text="Save" CssClass="publish" />
And then the function should work like it is:
protected void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
}
Please replace code as following code..
void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked==True)
{
newsItem.IsDraft = 1;
}
}
Try adding onclick="PublishButton_Click" in the button field on the form. And I don't know if it makes a difference, but generated event handlers are protected void.
For me the best solution in the end has been to create 2 separate pages: 1 for editing a news articles & 1 for a new news article. So Ill never then be in the position of a new news data object being created when the page reloads.
Both page return to the article index list page when the save button is pressed and that seems to work with being able to save the state of the draft checkbox and then show the state on the edit page.
The checkbox.checked isn't used in the context you want it to (this is a boolean that if true, will make the checkbox look checked).
What you could do is to use instead a checkboxlist. Then you could do the following:
foreach(Listitem li in CheckBoxList1.Items)
{
if (li.Selected)
{
NewsItem.Isdraft = 1;
}
}

Persistent dynamic control in ASP.Net

<asp:Button onclick="Some_event" Text="Add TextBox" ID="id1" runat="server" />
//once clicked:
<asp:TextBox ID="txt1" ......></asp:TextBox>
//when clicked again:
<asp:TextBox ID="txt1" ......></asp:TextBox>
<asp:TextBox ID="txt2" ......></asp:TextBox>
//and so on...
Is there a way to create dynamic controls which will persist even after the postback? In other words, when the user clicks on the button, a new textbox will be generated and when clicks again the first one will remain while a second one will be generated. How can I do this using asp.net ? I know that if I can create the controls in the page_init event then they will persist but I dont know if it possible to handle a button click before the page_init occurs, therefore there must be another way.
Yes, this is possible. One way to do this using purely ASP.NET (which seems like what you're asking for) would be to keep a count of the TextBox controls that you have added (storing that value in the ViewState) and recreate the TextBox controls in the Page_Load event. Of course, nowadays most people would probably use Javascript or jQuery to handle this task client side, but I put together a quick example to demonstrate how it works with postbacks:
Front page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicControls.aspx.cs" Inherits="MyAspnetApp.DynamicControls" EnableViewState="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
<asp:Button ID="btnWriteValues" runat="server" Text="Write" OnClick="btnWriteValues_Click" />
<asp:PlaceHolder ID="phControls" runat="server" />
</div>
</form>
</body>
</html>
Code behind:
using System;
using System.Web.UI.WebControls;
namespace MyAspnetApp
{
public partial class DynamicControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Recreate textbox controls
if(Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int) count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void AddTextBox(int index)
{
var txt = new TextBox {ID = string.Concat("txtDynamic", index)};
txt.Style.Add("display", "block");
phControls.Controls.Add(txt);
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void btnWriteValues_Click(object sender, EventArgs e)
{
foreach(var control in phControls.Controls)
{
var textBox = control as TextBox;
if (textBox == null) continue;
Response.Write(string.Concat(textBox.Text, "<br />"));
}
}
}
}
Since you are recreating the controls on each postback, the values entered into the textboxes will be persisted across each postback. I added btnWriteValues_Click to quickly demonstrate how to read the values out of the textboxes.
EDIT
I updated the example to add a Panel containing a TextBox and a Remove Button. The trick here is that the Remove button does not delete the container Panel, it merely makes it not Visible. This is done so that all of the control IDs remain the same, so the data entered stays with each TextBox. If we were to remove the TextBox entirely, the data after the TextBox that was removed would shift down one TextBox on the next postback (just to explain this a little more clearly, if we have txt1, txt2 and txt3, and we remove txt2, on the next postback we'll create two textboxes, txt1 and txt2, and the value that was in txt3 would be lost).
public partial class DynamicControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void btnWriteValues_Click(object sender, EventArgs e)
{
foreach(var control in phControls.Controls)
{
var panel = control as Panel;
if (panel == null || !panel.Visible) continue;
foreach (var control2 in panel.Controls)
{
var textBox = control2 as TextBox;
if (textBox == null) continue;
Response.Write(string.Concat(textBox.Text, "<br />"));
}
}
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int) count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void AddTextBox(int index)
{
var panel = new Panel();
panel.Controls.Add(new TextBox {ID = string.Concat("txtDynamic", index)});
var btn = new Button { Text="Remove" };
btn.Click += btnRemove_Click;
panel.Controls.Add(btn);
phControls.Controls.Add(panel);
}
private void btnRemove_Click(object sender, EventArgs e)
{
var btnRemove = sender as Button;
if (btnRemove == null) return;
btnRemove.Parent.Visible = false;
}
}
I read an article by Scott Mitchell that explains that ViewState only persists changed control state across post-back, and not the actual controls themselves. I did not have your exact scenario, but a project I was working on required dynamically added user controls and I had to add them on every postback. In that case, it is still useful to create them in Init so that they can retain their state. Here is the link: Understanding ASP.NET View State. Check section “View State and Dynamically Added Controls”.
You may have to keep track of all the controls that you are adding (in session state for example) and re-create them on post back. I just did a small test where I keep a List<string> of all the Textbox ids in Session. On postback, I recreate all the textboxes.

Categories