Category Archives: CustomValidator

[RESOLVED] listbox with optgroup

is there way to do listbox with optgroup?
i tried just making a header row with different styles but it is still selectable. enabled for that row makes it invisible.
i dont know of a way to use just a plain <select with runat=server and populate the items from code behind.

I did find someones dll that has this ability in their user control but i get a security trust fail when trying to run it. I cannot figure out how to tell the web.config that the dll is safe to run.

 

Doug 

http://weblogs.asp.net/jeff/archive/2006/12/27/dropdownlist-with-optgroup.aspx

 

Check Comment of -  Ben Sloan

The answer is not to use attributes as you suggest, but instead to set the "value" of the listitem which is to be the group header. Set it to something very unlikely to be used again like "$$GROUPHEADER$$GROUPHEADER$$"

Your test against the attribute (to see whether it is null) then becomes: "If item.Value = "$$GROUPHEADER$$GROUPHEADER$$" Then"

Next is to make it a bit easier for the programmer to add groups without having to remember this value string. To do this, I created a class called "OptionGroup" (I'm sure you can work out the contents of it) and then added a public sub on the control you wrote:

       Public Sub AddOptionGroup(ByVal og As OptionGroup)

           Dim optGrpTitle As New ListItem(og.GroupName, "$$GROUPHEADER$$GROUPHEADER$$")

           Me.Items.Add(optGrpTitle)

           For Each li As ListItem In og.Items

               Me.Items.Add(New ListItem(li.Text, li.Value))

           Next

       End Sub

To then add groups in an .aspx page:

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

       If Not IsPostBack Then

           Dim G1Items As New ListItemCollection

           G1Items.Add(New ListItem("G1V1", "G1V1"))

           G1Items.Add(New ListItem("G1V2", "G1V2"))

           G1Items.Add(New ListItem("G1V3", "G1V3"))

           Dim G2Items As New ListItemCollection

           G2Items.Add(New ListItem("G2V1", "G2V1"))

           G2Items.Add(New ListItem("G2V2", "G2V2"))

           G2Items.Add(New ListItem("G2V3", "G2V3"))

           Dim og1 As New OptionGroup("Group1", G1Items)

           Dim og2 As New OptionGroup("Group2", G2Items)

           Me.ddlTest.AddOptionGroup(og1)

           Me.ddlTest.AddOptionGroup(og2)

       End If

   End Sub

Except for that the code remains the same, and works perfectly across postbacks.

This is because the value property of the items does persist in viewstate, I suppose.

thx for that suggestion. I finally found out my problems with adding in someones dll. I had to change the app pool to run under NetworkService :) 

If you want to work w/ optgroup -- you need to use CustomValidator for Validation

Request.Form to get that value on server end

And throw JS from codebehind to update that control

Something along this line

<select name="opt1" id="opt1" >
        <option selected="selected" value="1">Select One</option>
        <optgroup label="aaaa">
        <option value="2">z1</option>
        <option value="3">z2</option>
        <option value="4">Z3</option></optgroup>
        <optgroup label="bbbb">
        <option value="5">X1</option>
        <option value="6">X2</option>
        </optgroup>
       
    </select>


//To get value at server end
int y1  = Int32.Parse(Request.Form["opt1"].ToString());


//To update that control from codebehind
ScriptManager.RegisterStartupScript(this, this.GetType(), "starScript", "Updateopt('" + x1 + "');", true);

[RESOLVED] Detect text file during uplaod

Hi,

on my website I have file uploading (only text files). How to detect correct file type? 

Reading first 8 bytes doesn't works here because there are text files.

Any ideas?

Did you try checking the extension?

string extenstion = Path.GetExtension(filename);
        if (extenstion != ".txt")
        {
        }

This approach is not safe.

Hi,

olo21

How to detect correct file type? 

There's several methods you can do to control the type of upload file.

One is to use validation controls, it can force the checking to be done on the client. Of course, it need the browser allow client side use of the validation controls.

Check:http://www.developer2blog.com/post/2011/02/07/File-Upload-Control-File-Type-Validation.aspx

Second is use server side code to check file type. This method allow the file upload to server, but before save the file, it will first check the type on server.

You can check:http://www.beansoftware.com/ASP.NET-FAQ/FileUpload-Validation.aspx

If you want to a more secure way. I suggest to use both client side and server side validation

Hope this can help you.

hi..

when uploading ,you wanto check the file extension means you have to use httpfileuploaded,try this link to know more aboout this function 

http://vbdotnetaddict.blogspot.com/2011/02/upload-image-or-file-into-database-in.html

Use RegularExpressionValidator and also in case use customValidator with serverside function to actually validate the text file...

Thanks.

All your solutions are good but there is one disadvantage: they work based on a file extension. Is any other way to detect text files?

Hi,

olo21

they work based on a file extension

If you do not want to check the extension. The way I can think out is to use the server code: FileUpload1.PostedFile.ContentType.

After text files post to server. Use above code to check the mine type(text/plain). But also notice that, if user changed the file extension manually. The mine type will not be correct as we expect. Seems that if I changed the txt to jpg or pdf, the mine type is correct. But like .doc or other extension. The type will changed also.

Hope this can help you.

Hi,

olo21

they work based on a file extension

If you do not want to check the extension. The way I can think out is to use the server code: FileUpload1.PostedFile.ContentType.

After text files post to server. Use above code to check the mine type(text/plain). But also notice that, if user changed the file extension manually. The mine type will not be correct as we expect. Seems that if I changed the txt to jpg or pdf, the mine type is correct. But like .doc or other extension. The type will changed also.

Hope this can help you.

[RESOLVED] compare and validate the value in textbox and dropdownlist

<div>hi guys, <div>I hav ADMIN_ID textbox and ROLES dropdownlist, when I enter ADMIN_ID such as staff001 then at ROLES dropdownlist I must select "staff" else display an error msg, for example staff002 with roles manager.</div> <div>Can guide me how to do this and i'm using C#?</div> <div>Thanks in Advance.</div> </div>

Hi

I would suggest to have 2 dropdown lists. One for AdminID and one for Roles. Whenever user selectes a particular staffid, the Roles dropdown list should be filled in with appropriate roles. This will save you from extra validation. Ofcourse you need to have some association between staff and roles somewhere in your database, where every staff member has allowed roles.

Alternatively, you can put hard coded if conditions. Where you check for every staff member the assigned role like:

if (txtStaff.Text == "staff001" && ddlRoles.SelectedValue!="staff")
{
     labelError.Text = "Invalid Role";
}

But still this is not the right approach. So I would strive on using the 1st one.

you can do it with a customvalidator...either with clientside function or with server side validation function....

basically you have to get the string staff001 and then check for 'contains' with DDL selectcted text...

str1.contains(str2)...something like that...

PS - this is not the best way of doing this....alternatively you can use Asp.net membership with roles...click on webforms tab on top of this page and then navigate to security section to get more info....

Thanks.

<div style="font-family: 'Segoe UI', Tahoma, Verdana, Arial, Helvetica; font-size: 13px; color: #505050; height: 100%; text-align: justify; background-image: url(http://www.eggheadcafe.com/images/template2/white.gif) !important; background-attachment: initial !important; background-origin: initial !important; background-clip: initial !important; background-color: #2f2f2f; word-wrap: break-word !important; background-position: 0% 0% !important; background-repeat: repeat repeat !important; padding: 0px; margin: 0px;">If I enter ADMIN_ID "staff005" or "staff050" or any ADMIN_ID which format is "staff"+"3 digit" then how can i compare and do the validation?</div>

<div style="font-family: 'Segoe UI', Tahoma, Verdana, Arial, Helvetica; font-size: 13px; color: #505050; height: 100%; text-align: justify; background-image: url(http://www.eggheadcafe.com/images/template2/white.gif) !important; background-attachment: initial !important; background-origin: initial !important; background-clip: initial !important; background-color: #2f2f2f; word-wrap: break-word !important; background-position: 0% 0% !important; background-repeat: repeat repeat !important; padding: 0px; margin: 0px;">If I enter ADMIN_ID "staff005" or "staff050" or any ADMIN_ID which format is "staff"+"3 digit" then how can i compare and do the validation?</div>

I think i mentioned about the same validation....

use a custom validator.....

Get the text from the textbox and the selected text from the DDL...then compare it in the validation function written for custom validator....

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx

Thanks.

Put a RequiredFieldvalidator for the DropDownList.

On the client side textBox OnBlur event , change the ddl selected Value.

With that said above -- during form submit if for some reason, the ddl is left unselected , the RequiredField Validator will fire & alert the user.

[RESOLVED] Check Box Select All Validation

<input id="ContentPlaceHolder1_chkAll" name="ctl00$ContentPlaceHolder1$chkAll" type="checkbox" />


<input id="ContentPlaceHolder1_CheckBoxList1_0" value="1" name="ctl00$ContentPlaceHolder1$CheckBoxList1$0" type="checkbox" />
<input id="ContentPlaceHolder1_CheckBoxList1_1" value="2" name="ctl00$ContentPlaceHolder1$CheckBoxList1$1" type="checkbox" />
<input id="ContentPlaceHolder1_CheckBoxList1_2" value="3" name="ctl00$ContentPlaceHolder1$CheckBoxList1$2" type="checkbox" />
<input id="ContentPlaceHolder1_CheckBoxList1_3" value="4" name="ctl00$ContentPlaceHolder1$CheckBoxList1$3" type="checkbox" />
<input id="ContentPlaceHolder1_CheckBoxList1_4" value="5" name="ctl00$ContentPlaceHolder1$CheckBoxList1$4" type="checkbox" />

 

<asp:CheckBox ID="chkAll" runat="server" onclick="return CheckUnCheckAll();" Text="Select All" />
                                    <hr />
                                    <asp:CheckBoxList ID="CheckBoxList1" onclick="return CheckUnCheckList();" runat="server">
                                        <asp:ListItem Value="1" Text="Forecast & Sales Price Data"></asp:ListItem>
                                        <asp:ListItem Value="2" Text="Production & BPP Price Data"></asp:ListItem>
                                        <asp:ListItem Value="3" Text="Inventory & Tankage Data"></asp:ListItem>
                                        <asp:ListItem Value="4" Text="Transit Time Data"></asp:ListItem>
                                        <asp:ListItem Value="5" Text="Transportation Modes Data"></asp:ListItem>
                                    </asp:CheckBoxList>
                                    <asp:CustomValidator ID="CustomValidator1" ClientValidationFunction="sandValidation"
                                        ForeColor="Red" Display="Dynamic" runat="server" ErrorMessage="Please Check atleast 1 Data for upload."
                                        ToolTip="Please Check atleast 1 Data for upload." ValidationGroup="vgSand">*</asp:CustomValidator>

 

 

<script type="text/javascript" language="javascript">
        function sandValidation(sender, args) {
            var chkControlId = '<%=CheckBoxList1.ClientID%>'
            var options = document.getElementById(chkControlId).getElementsByTagName('input');
            var ischecked = false;
            args.IsValid = false;
            for (i = 0; i < options.length; i++) {
                var opt = options[i];
                if (opt.type == "checkbox") {
                    if (opt.checked) {
                        ischecked = true;
                        args.IsValid = true;
                    }
                }
            }
        }
        function CheckUnCheckAll() {
            var chkControlId = '<%=CheckBoxList1.ClientID%>'
            var options = document.getElementById(chkControlId).getElementsByTagName('input');

            var temp = '<%=chkAll.ClientID%>'
            var _chkControl = document.getElementById(temp);

            if (_chkControl.checked == true) {
                for (i = 0; i < options.length; i++) {
                    var opt = options[i];
                    if (opt.type == "checkbox") {
                        opt.checked = true;
                    }
                }
            }
            else {
                for (i = 0; i < options.length; i++) {
                    var opt = options[i];
                    if (opt.type == "checkbox") {
                        opt.checked = false;
                    }
                }
            }
            return true;
        }
        function CheckUnCheckList() {
           
            var chkControlId = '<%=CheckBoxList1.ClientID%>'
            var options = document.getElementById(chkControlId).getElementsByTagName('input');
            var ischecked = false;
            var isUnCheck = false;
            //            args.IsValid = false;
            for (i = 0; i < options.length; i++) {
                var opt = options[i];
                if (opt.type == "checkbox") {
                    if (opt.checked) {
                        ischecked = true;
                        //                        args.IsValid = true;
                    }
                    else {
                        isUnCheck = true;
                    }
                }
            }
           
            if (isUnCheck == true) {
                var temp = '<%=chkAll.ClientID%>'
                var _chkControl = document.getElementById(temp);
                _chkControl.checked = false;

            }
        }
    </script>

Whats the problem you are facing. Your code is working fine.

[RESOLVED] Dropdownlist not keeping the selected value after submit

I'm a newbie. So, Please accomodate  if I am asking for some little thing.

In my form, I've many input elements one of which is, a radio button group with Autopostback set to true. After selecting one item from the radio button, the drop down list below fetches values from database and is refreshed. I choose some value in the dropdown list and submit the form. I've many server side validation controls. When I submit the form, if any of the server validation fails, it'll show the error message in the form. But the value I choose in the dropdown list disappears and it shows the first value of the dropdown list.

How to show the selected value in the list after submission of form?

Below is the partial code from my form. When I type anything other than "Hello" is the "Comments" text box, it will show the error message. I know I can use, other validators to check this. But purposely I want to use Customvalidator.

Any help is appreciated. Thks for your time

 

My C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Text;
using System.IO;




public partial class Mytest : System.Web.UI.Page
{




    protected void Page_Load(object sender, EventArgs e)
    {


        if (!IsPostBack)
        {
            Populate1();


        }


        Populate2();




    }




    public void Populate1()
    {
        SqlConnection conn1 = new SqlConnection();
        conn1.ConnectionString = ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;
        conn1.Open();
        string query = "SELECT * FROM SuggKeyCat";
        SqlCommand cmd = new SqlCommand(query, conn1);


        SqlDataReader ddlValues;
        ddlValues = cmd.ExecuteReader();
        CatList.DataSource = ddlValues;
        CatList.DataValueField = "KeyCat_ID";
        CatList.DataTextField = "KeyCat_Desc";
        CatList.DataBind();


        cmd.Connection.Close();
        cmd.Connection.Dispose();


    }




    public void Populate2()
    {


        BenList.Items.Clear();


        SqlConnection conn2 = new SqlConnection();
        conn2.ConnectionString = ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;
        conn2.Open();
        string query2 = "SELECT * FROM SuggCat where SCate = '" + CatList.Text.Trim() + "' order by Cat_ID";
        SqlCommand cmd2 = new SqlCommand(query2, conn2);


        SqlDataReader ddlValues2;
        ddlValues2 = cmd2.ExecuteReader();
        BenList.DataSource = ddlValues2;
        BenList.DataValueField = "Cat_ID";
        BenList.DataTextField = "Cat_Desc";
        BenList.DataBind();
        cmd2.Connection.Close();
        cmd2.Connection.Dispose();


    }




    protected void ValidateServerSide1(object source, ServerValidateEventArgs args)
    {


        if (UrComments.Text != "hello" )
        { args.IsValid = false;}
        else
        { args.IsValid = true; }
    }




    



    protected void DataProcess(object sender, EventArgs e)
    {


        if (Page.IsValid)
        {
            //do something


        }


    }


}



 

My ASP.net code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Mytest.aspx.cs" Inherits="Mytest" %>

<!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 id="Head1" runat="server">
    <title></title>
    <link rel="Stylesheet" href="style.css" type="text/css" />
</head>
<body>

    <form id="SuggForm" runat="server">    
    <asp:Table ID="Table1" runat="server" BorderColor="#8B8B8B" BorderStyle="solid"  BorderWidth="1px" cellSpacing="10" CellPadding="4" Width="50%"> 
      
    
        <asp:TableRow ID="TableRow8" runat="server" VerticalAlign="Middle" HorizontalAlign="Left">
            <asp:TableCell ID="TableCell15" Width="20%" runat="server" VerticalAlign="Top">
                <asp:Label ID="Label13" runat="server" Text="Category 1:" Font-Names="Verdana" ForeColor="#575757" Font-Size="0.7em" Font-Bold="True"></asp:Label> 
            </asp:TableCell>    
            <asp:TableCell ID="TableCell16" Width="79%" runat="server" VerticalAlign="top">        
                <asp:RadioButtonList AutoPostBack="true" RepeatLayout="Table" RepeatColumns="3" BorderColor="#CFCFCF" CellSpacing="2" CellPadding="2" BorderWidth="1px" BorderStyle="Ridge" Width="50%" Font-Names="verdana" Font-Size="11.5px" ForeColor="#575757"  ID="CatList" runat="server"></asp:RadioButtonList>
           </asp:TableCell>
        </asp:TableRow>
    
    
        <asp:TableRow ID="TableRow12" runat="server" VerticalAlign="Middle" HorizontalAlign="Left">
            <asp:TableCell ID="TableCell29" Width="20%" runat="server" VerticalAlign="Top">
                <asp:Label ID="Label19" runat="server" Text="Category 2:" Font-Names="Verdana" ForeColor="#575757" Font-Size="0.7em" Font-Bold="True"></asp:Label> 
            </asp:TableCell>    
            <asp:TableCell ID="TableCell58" Width="79%" runat="server" VerticalAlign="Top">        
                 <asp:DropDownList BackColor="#ffffff" Font-Names="verdana" Font-Size="0.7em" ForeColor="#575757" ID="BenList" runat="server" Width="100%" Height="40px">
                 </asp:DropDownList>
            </asp:TableCell>
        </asp:TableRow>   
    
    
        <asp:TableRow ID="TableRow2" runat="server" VerticalAlign="Middle" HorizontalAlign="Left">
            <asp:TableCell ID="TableCell3" Width="20%" runat="server" VerticalAlign="Top">
                <asp:Label ID="Label3" runat="server" Text="Comments:" Font-Names="Verdana" ForeColor="#575757" Font-Size="0.7em" Font-Bold="True"></asp:Label> 
                <asp:TextBox TextMode="MultiLine" BackColor="#ffffff" ID="UrComments" Font-Names="verdana" Font-Size="0.7em" ForeColor="#575757" Rows="5" Width="100%" runat="server"></asp:TextBox>
                <asp:CustomValidator id="CustomValidator1" runat="server" OnServerValidate="ValidateServerSide1" ControlToValidate="UrComments" ErrorMessage="Explanation required."  Font-Names="Verdana" ForeColor="#FF3300" Font-Size="0.7em" Font-Bold="False"></asp:CustomValidator>
            </asp:TableCell>  
        </asp:TableRow>
              
       
        <asp:TableRow ID="TableRow10" runat="server" VerticalAlign="Middle" HorizontalAlign="Left">
            <asp:TableCell ColumnSpan="3" HorizontalAlign="right" ID="TableCell19" Width="30%" runat="server" VerticalAlign="Top">
              <asp:ImageButton AlternateText="Submit" ID="SubImg" runat="server" ImageUrl="images/Sub.jpg" OnClick="DataProcess" /> 
          </asp:TableCell>  
        </asp:TableRow>        
        </asp:Table>
        
    </form>  
    
</body>
</html>


 

You have to include populate2 in if (!IsPostBack) as well with the populate1.

That is your Page_Load event will look like

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Populate1();
            Populate2();
        }
    }



Thanks for your reply.

If I do this, When the page is loaded for first time, the dropdown list is empty. 

Also, when I choose some option from radiobutton, again the dropdown list is empty. 

You can simply store the selected value in a session variable and again  set the value selected tot he dropdown  on pageload checking for the PagePostback.

Sorry, Can you elaborate a bit? At what point I need to create  the session variable and how to make it as a selected item when the page is submitted? Thanks

This is not possible using the code you have shown.

Is this ALL code you are having for this page? Is there any other place where you are binding the Dropdownlist?

There is no other place I am binding the dropdownlists.

Ofcourse, I've some more code, but on the "DataProcess" section after the form is successfully submitted, like sending email, updating database etc which is not relevant here.

When I enable and see the traces, I could see under "Form Collection" data - For example, Catlist =1 and Benlist = 3, if I choose item 1 in the radio button and item 3 in the dropdown list. This happens after I click Submit button.

But I suspect that when the page is reloaded after form submission, the dropdown list goes back to default.

Thanks all for your time.

Any one have any idea?

Hi,

invoke method Populate2(); on CatList SelectedIndexChanged event..

 

Regards..

are you sure that you have set AutopostBack property of dropdownlist to true ?

When I add OnSelectedIndexChanged="Populate2();" to the Catlist, I go this error Compiler Error Message: CS1026: ) expected Source Error: Line 19: </asp:TableCell> Line 20: <asp:TableCell ID="TableCell16" Width="79%" runat="server" VerticalAlign="top"> Line 21: <asp:RadioButtonList AutoPostBack="true" RepeatLayout="Table" RepeatColumns="3" BorderColor="#CFCFCF" CellSpacing="2" CellPadding="2" BorderWidth="1px" BorderStyle="Ridge" Width="50%" Font-Names="verdana" Font-Size="11.5px" ForeColor="#575757" ID="CatList" runat="server" OnSelectedIndexChanged="Populate2();"> Line 22: </asp:RadioButtonList> Line 23: </asp:TableCell>

When I add  AutoPostBack="true"  to dropdown list, which method I need to evoke? If there are 2 auto post back, how do I differentiate?

 

Thanks

 

OnSelectedIndexChanged="Populate2"

no ()....the previous posters suggestion was good....you can bind the DDL in RBL selectedIndexChanged event....

Thanks.

I'm sorry.

Couldn't get your point. Since I've posted my code, can you explain a bit more?

Thanks.

 

Hi,

 

  If you want to populate the dropdown value only when changing the radiobuttonlist value, then you can do the following things

 

      Delete the Populate2() from the page load. Then add a SelectedIndexChanged function for the radiobuttonlist. Populate the dropdown value in that function, ie call the function Populate2().

 

Mahesh 

Hi maybe you need to Hold the selected value of dropdownlist in postback before you populate them.  After you populate them set the selected index = to you ddl value

 

Modifie code like this

 

 

public partial class points : System.Web.UI.Page
    {
     private int selectedIndex;

        protected void Page_Load(object sender, EventArgs e)
        {
            SetMyDropDownSelectedIndex();
            Populate1();
            CatList.SelectedIndex = selectedIndex;
            Populate2();
         
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Do post back
        }
        private void SetMyDropDownSelectedIndex()
        {

           DropDownList ddl = Page.FindControl("CatList") as DropDownList;

            y = Convert.ToInt32(ddl.SelectedValue);


           


        }
    }

 

 

 

 

Thanks for your time.

But your code doesn't help to solve my problem.

By the way, your code is truncated in the forum, don't knwo why.

But I got your code in my mailbox and used that. There were some errors in your code (Like the method name not correctly used, what is"y", Catlist instead of Benlist). But I corrected those and run. But not my expected result.

Any other expert opinions?

 

Have you correted this line

y = Convert.ToInt32(ddl.SelectedValue);

to this

selectedIndex = Convert.ToInt32(ddl.SelectedValue);


Or try this

 protected void DataProcess(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            //do something

        }
else{
Populate1();
Populate2();
ddl.SelectedIndex = selectedIndex;
}

    }

Here i have tested this code and it works to keep the dropdown selected Stateafter each postback

 

 

private int selectedIndex;

        protected void Page_Load(object sender, EventArgs e)
        {

            GetIndex();

            if (!IsPostBack)
            {
                Populate1();

            }

            Populate2();



            BenList.SelectedIndex = selectedIndex;


        }
        public void Populate1()
        {
           

        }


        private void GetIndex()
        {
            

            selectedIndex = BenList.SelectedIndex;

        }


        public void Populate2()

        {
            BenList.Items.Clear();
            //This is just to Populate the  Dropdown
            string [] ddlval = {"Swiming","Cricket","Rugby","Football"};


            for (int x = 0; x < ddlval.Length; x++)
            {

                BenList.Items.Add(ddlval[x].ToString());
            }
         

        }

 

Hi,

Add the following code as function and Call where ever u r losing

string selectedValue = HiddenFieldVar.Value;
        BenList.SelectedIndex = 0;
        for (int i = 0; i < BenList.Items.Count; i++)
        {
            if (BenList.Items[i].Value == "selectedvalue")
            {
                BenList.SelectedIndex = i;
            }
        }

 

Thanks

Sree

Mark it as Answer if it helps. So that Others Can not waste their time

use the viewstate property in drop down selected index for both the drop down.

private int selectedIndex;
 
        protected void Page_Load(object sender, EventArgs e)
        {
 
            GetIndex();
 
            if (!IsPostBack)
            {
                Populate1();
 
            }
 
            Populate2();
 
 
 
            BenList.SelectedIndex = selectedIndex;
 
 
        }
        public void Populate1()
        {
            
 
        }
 
 
        private void GetIndex()
        {
             
 
            selectedIndex = BenList.SelectedIndex;
 
        }
 
 
        public void Populate2()
 
        {
            BenList.Items.Clear();
            //This is just to Populate the  Dropdown
            string [] ddlval = {"Swiming","Cricket","Rugby","Football"};
 
 
            for (int x = 0; x < ddlval.Length; x++)
            {
 
                BenList.Items.Add(ddlval[x].ToString());
            }
          
 
        }

magic mushroom,

Big thanks for solving the problem.

It works now.

 

 

 

Im Glad it worked for you