Archive

Posts Tagged ‘ASP .Net’

Retain the value of a dynamic control on post back

January 25th, 2010 14 comments

I heard this question several time that how you can retain the value of dynamically created controls on postbacks. You might see this before that when you create dynamic controls either in GridView or page. When you do postback, you cannot find the controls in page or GridView.

If you want your dynamic controls to work you can create them on page_load or page_init methods. But in some cases you have to create controls on some control event other than page_laod or page_init. In these cases you can follow my blog to retain the values of dynamic controls on postbacks.

In my case I have a button named btnSetParameters. On click event I’m creating controls in a GridView column. I have an ASP .Net panel in that column. My code is creating dynamic controls and then adding them to panel. But on postback I couldn’t found these controls in GridViewRow by their IDs. I need their values on postback.

For this I have created an ArrayList to keep controls.

Private objControlsList As New ArrayList

Then on RowDataBound where I was creating dynamic controls I added some code to add these controls in ArrayList. Here is an example of adding a TextBox in ArrayList. ASP Panel in GridViewRow name is pnlControls.

Dim txtValue As New TextBox
txtValue.ID = “txtValue1″
CType(e.Row.FindControl(“pnlControls”), Panel).Controls.Add(txtValue)
objControlsList.Add(txtValue)

Do the same for all the dynamic controls and add them on ArrayList. You can even put custom controls in this ArrayList. After adding all the controls, put this ArrayList in Session.

Session.Add(“ControlsList”, objControlsList)

Now on page postback, use the controls from the ArrayList. Use the UniqueID to pick the values from the ViewState for orginal controls.

Dim txtSaved As TextBox = CType(objControlsTempList(counter), TextBox)
txtValue.Text = Request.Form(txtSaved.UniqueID).ToString()
counter += 1

For dynamic DropDownlist control you can use this piece of code.

Dim ddlSaved As DropDownList = CType(objControlsTempList(counter), DropDownList)
ddlSaved.SelectedValue = Request.Form(ddlSaved.UniqueID).ToString()
counter += 1

For radio buttons you can use this piece of code. You must define a group name while creating the radio buttons to use this code.

Dim rdSaved As RadioButton = CType(objControlsTempList(counter), RadioButton)
Dim radioName As String = (rdSaved.ClientID).Remove(rdSaved.ClientID.LastIndexOf(“_”)).Replace(“_”, “$”) + “$” + rdSaved.GroupName
If Request.Form(radioName) <> Nothing Then
        selectedValue = Request.Form(radioName).ToString()
End If

Now you can match this selectedValue with radio buttons in the Panels, to find the selected radio button.

For CheckBoxe controls you can use this code.

Dim chSaved As CheckBox = CType(objControlsTempList(counter), CheckBox)
If Request.Form(chSaved.UniqueID) <> Nothing Then
        chSaved.Checked = True
Else
        chSaved.Checked = False
End If

Finally, you can use this code for dynamic custom control. It’s a bit tricky to find the value. I know the structure of my custom user control. It is a custom date control. It is actually creating two DropDownList controls for day and month part of date. And it is also creating a TextBox control for Year part of the date. Here is the piece of code I use to get the selected value of dynamic custom control on postback.

Dim dtSaved As CustomDate = CType(objControlsTempList(counter), CustomDate)
Dim cntlName As String = “”
Dim selectedDate As String = “”
cntlName = (dtSaved.ClientID + “_ddlDay”).Replace(“_”, “$”)
selectedDate = Request.Form(cntlName).ToString()

cntlName = (dtSaved.ClientID + “_ddlMonth”).Replace(“_”, “$”)
selectedDate += “/” + Request.Form(cntlName).ToString()

cntlName = (dtSaved.ClientID + “_txtYear”).Replace(“_”, “$”)
selectedDate += “/” + Request.Form(cntlName).ToString()

dateCtrl.DateValue = Date.Parse(selectedDate)
counter += 1

Hope it will help someone, creating dynamic controls and retain the values on postbacks.

Cheers

Disable submit button from client side

October 30th, 2009 5 comments

It seems very easy to disable ASP .Net submit button, but there are a lot of complications to perform this seemingly small thing. Usually when you disable ASP .Net submit button, it stops further processing. So if you disable button from JavaScript onclick function, it will not do postback. Sometime you want to disable submit button before page postback, for example if you have a file upload form and your code take some time to upload a big file, you might like to disable submit button. There are different solutions to solve this issue.
First solution is you can call the postback from client side JavaScript. For this I will prefer to write the JavaScript code from code behind file. You can attach an attribute like this

submit.Attributes.Add(“onclick”, “this.disabled=true;” + Page.ClientScript.GetPostBackEventReference(submit, “”));

But the problem with this solution is, if you have ASP .Net validation implemented on the controls. Even if it fails validation it fires post back event. In my form I also had ASP .Net validator. So I choose another option.
Solution is very simple, create another button with same text value and keep hidden. On client click of actual submit button hide submit button and show the hidden button. Make sure hidden button should be disabled. You can disable it from JavaScript as well. In this way user will not get idea that it’s a different button and it will also give an effect of disabled button.
Now if you are using ASP .Net validation, you would probably like to disable submit button when page validation is successful. So here is the code you can use.

protected override void OnInit(EventArgs e)
{
Button Submit = (Button)FindTemplateControl(“submit”);
Button Cancel = (Button)FindTemplateControl(“cancel”);
Button HiddenSubmit = (Button)FindTemplateControl(“hiddensubmit”);

string script = “if (!(typeof (ValidatorOnSubmit) == \”function\” && ValidatorOnSubmit() == false))”;
script += “{ “;
script += @”document.getElementById(‘” + Submit.ClientID + “‘).style.display=’none’;”;
script += @”document.getElementById(‘” + HiddenSubmit.ClientID + “‘).style.display=’inline’;”;
script += @”document.getElementById(‘” + HiddenSubmit.ClientID + “‘).disabled=true;”;
script += @”document.getElementById(‘” + Cancel.ClientID + “‘).disabled=true;”;
script += @” } “;
script += @”else “;
script += @”return false;”;

Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), “DisableSubmitButton”, script);
}

Have fun :)

Success message using ASP .Net validators

October 29th, 2009 2 comments

Recently we have implemented a form containing file upload controls. We have used ASP .Net validators to validate fields. In ASP .Net validation you can display error message in Recently we have implemented a form containing file upload controls. We have used ASP .Net validators to validate fields. In ASP .Net validation you can display error message in ValidationSummary control, but you can’t display success message. My case was I had to display a message to users before file upload start. And obviously this message needs to appear after successful page validation and before page do a post back. So in case file upload take some time, user can see a message that file upload processing has been started.
Here how I achieve it. When you use ASP .Net validator in page, your ASP .Net validator generates some JavaScript code in page. If you see the source of html page you can see this function.

function WebForm_OnSubmit()
{
    if (typeof(ValidatorOnSubmit) == “function” && ValidatorOnSubmit() ==false)
        return false;
    return true;
}

Now you need to write some code for on submit function. Create a div in your page and add your message in it. Set the display as  none in style property. Here is the div I used for my file upload form.

<div id=”successmessage” style=”display:none; color:Red>
“Please wait for your confirmation message while we upload your files (for large files this may take a few minutes)”
</div>

Now add this piece of code in cs file.

protected override void OnInit(EventArgs e)
{
    string script = “if (typeof (ValidatorOnSubmit) == \”function\” && ValidatorOnSubmit() == false)”;
    script += @”return false;”;
    script += @”else “;
    script += @”document.getElementById(‘successmessage’).style.display=’block’”;
    Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), “SuccessMessage”, script);
}

That’s all, now when you press submit button, it validates page and display success message if successful. After implementing this code your html page source will be like this

function WebForm_OnSubmit()
{
    if (typeof (ValidatorOnSubmit) == “function” && ValidatorOnSubmit() == false)
        return false;
    else
        document.getElementById(‘successmessage’).style.display=’block’;

    if (typeof(ValidatorOnSubmit) == “function” && ValidatorOnSubmit() == false)
        return false;
    return true;
}