Category Archives: ObjectDataSource

[RESOLVED] Using REQUEST("ListBoxName") to get values

So I have a master page and inside it is a content place holder. In that content place holder is a panel with a bunch of multi select list boxes. Under that panel is a button.

when I click the button, I want to use the REQUEST object to get a comma separated string of my list box selected values. It does not seem to create a string though.. I have done this before on just plain Webforms without a master page and it worked fine. Could you help explain what I am doing wrong??

This is a section of my code:


Protected Sub FilterButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        

        'Strings to store comma separated selections
        Dim MethodIDSelection As String
        MethodIDSelection = Request.QueryString("MethodNameLB")
                

        If MethodIDSelection = "" Then
            Label5.Text = "Method was blank"
        Else
            Label5.Text = MethodIDSelection
        End If
        

    End Sub


According to your wording above the button is on the Content Page with the ListBoxes.  Are you passing the query string to this page and you simply want to pre-select the items in the list boxes or you want to generate a query string from the selections to pass to another page?

If you are trying to generate a comma separated list can we see the code you used to create the ListBoxes?  If it is data driven then be sure you are reloading the data after the postback.  I also do not see any code to even loop through the listboxes and create a list.  I do recommend StringBuilder instead of String with a simple += because it is more efficient.

Sudo Code:

Dim MyString As New StringBuilder


For Each Item As ListItem In MyListBox
     If Item.Selected Then
          MyString.Append("," & Item.Text)
     End If
Next


Response.Redirect("NewPage.aspx?selected=" & MyString.ToString, False)

If you are trying to read the query string the above code should be in the Me.Load method handler.  Once the button is clicked it initiates a postback and will most likely loose the query string.

Sorry page lost formatting so I deleted it.

Sorry, I guess I missed out some information. I didn't mean to use the .QueryString. Just use Request("MethodNameLB"). Also, the data in the listbox is from an object datasource attached to a database. Here is the code for the entire ASPX page. Its pretty straightforward.


<%@ Page Title="" Language="VB" MasterPageFile="~/SuperPage.master" %>


<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>


<script runat="server">
    

    Protected Sub FilterButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)


        'Strings to store comma separated selections
        Dim MethodIDSelection As String
        MethodIDSelection = Request("MethodNameLB")
                

        If MethodIDSelection = "" Then
            MyLabel.Text = "Method was blank"
        Else
            MyLabel.Text = MethodIDSelection
        End If
        

    End Sub
    

</script>


<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="TitleContent" Runat="Server">
Test Page</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">


<div style="font-family: Verdana; font-size: small">
   

    <asp:ObjectDataSource ID="PersonalMethodsData" runat="server"
            OldValuesParameterFormatString="original_{0}" SelectMethod="GetPersonalMethodsDataByActive"
            TypeName="PersonalMethodsBLL"></asp:ObjectDataSource>
            





    <asp:ListBox ID="MethodNameLB" runat="server" DataSourceID="PersonalMethodsData"
                            DataTextField="MethodName" DataValueField="PersonalMethodID"
                            SelectionMode="Multiple"></asp:ListBox>
    <cc1:ListSearchExtender ID="MethodNameLB_ListSearchExtender" runat="server" PromptCssClass="searchExtender"
                            PromptPosition="Bottom" PromptText=""
    TargetControlID="MethodNameLB">
    </cc1:ListSearchExtender>
    <br />
    <asp:Label ID="MyLabel" runat="server" Text="Label"></asp:Label>
<asp:Panel ID="InputPanel" runat="server">
</asp:Panel>
<asp:Button ID="FilterButton" runat="server" Text="Filter View" onclick="FilterButton_Click" />


</div>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ScriptHolder" Runat="Server"></asp:Content>


Using just Request(key) is not nearly as efficient as specifying the actual source.  The Request(key) command will look through the Request.Forms, Request.QueryString, Request.Cookies, and Request.ServerVariables just to find a match.  If you want the application to create a comma separate list I would suggest using a session variable to maintain the data and not the Request object.  You should use a ViewState if you only need the data on that page.  To create the list though you don't need to assign the object to anything until the end.

Now I am not too familiar with ObjectDataSource controls but I do know for the selected items to remain you need to reload the data on postback from the previous source and not reload the data each time from the database.  If you load it each time it will clear the checked items before it ever runs the button click event.  I always load data in a BindData method similar to the code below.  It allows for easier debugging and less web code.  Hope this helps point you in a different direction that works.

Dim myData As DataTable


Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
     If Not IsPostBack Then
          BindData(True)
     Else
          myData = CType(ViewState("TableData"), DataTable)
     End If
End Sub


Private Sub BindData(Optional ByVal RefreshData As Boolean = False)
     If RefreshData Then
          myData = GetPersonalMethodsDataByActive()
          ViewState("TableData") = myData
     End If


     MethodNameLB.DataSource = myData
     MethodNameLB.DataBind()
End Sub


Protected Sub btnFilter_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFilter.Click
     Dim MyList As New StringBuilder
     For Each Item As ListItem In MethodNameLB
          If Item.Selected Then
               MyList.Append("," & Item.Value)
          End If
     Next
     If MyList.Length > 0 Then MyList.Remove(0, 1)
     Session("SelectedItems") = MyList.ToString
End Sub


 

This can be done without using Request object. Here's an example, which you may write in codebehind of your content page.


string strTemp1 = "";
foreach (ListItem item in ListBox1.Items)
{
     if (item.Selected == true)
     {
               
        strTemp1 += (strTemp1 == "") ? item.Value : "," + item.Value;
      }

I just figured using the request object would be easiest. But it doesn't seem to work if the listbox in inside of an update panel. My guess is because their is only a partial page postback and the request() never gets called.

My main goal is to try and simplify the code. I don't like the looping through method as it is messy and I have to due this on several list boxes. I have resorted to LINQ as an alternative but have ran into another problem I'm hoping someone can help me out with. I can use LINQ to get the either the .text of the list box items or the .value, but I don't know how to get both at the one time and return them into an array.

Anyhow this is what I have moved toward:

Dim TextString As String = ""
Dim ValueString As String = ""


Dim selItemsText = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select li.Text


Dim selItemsValue = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select li.Value


TextString = Join(selItemsText.ToArray, ",")
ValueString = Join(selItemsValue.ToArray, ",")


'I would like to do this using 1 LINQ statement selecting separate entities like this:


Dim TextString As String = ""
Dim ValueString As String = ""


Dim selItems = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select New With {.itemtext = li.Text, .itemVal = li.Value}


TextString = Join(selItems.itemtext.ToArray, ",")
ValueString = Join(selItems.itemVal.ToArray, ",")


I'm not sure if this is possible or not, or if my code is even accurate as I haven't tested it, but this is what I'm trying to accomplish. So if I had a listbox with the following data I would get the following strings:

listboxText - listboxValue - Selected

A - 1 - YES

B - 2 - NO

C - 3 - YES


TextString = "A,C"

ValueString = "1,3"




Note: I am using VB.net not C# or old versions of VB so an answer in VB.Net would be much appreciated. Thanks

Hi,

Hybird

I want to use the REQUEST object to get a comma separated string of my list box selected values. It does not seem to create a string though.. I have done this before on just plain Webforms without a master page and it worked fine.
 

According to your description ,for my experience the Request object can retrieve the values that the client browser passed to the server during an HTTP request.

As far as I know you can use Request["nameOfControl"] to get control's value. 

However ,if you use a master page ,the name of control(which is contained in the content page) is not the same as its'ID.

Thus,the code which as you mentioned in your post :Request("MethodNameLB") can not get the value.

I would like to suggest you to check the sample below which shows how to use Request object to get the value of the control which is contained in content page.

1.Code in master page(.master):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>


2.Code in content page(.aspx):

 

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script language="javascript" type="text/javascript">
    function GetNameOfListBox() {
        var listbox = document.getElementById("<%=ListBox1.ClientID %>");
        var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
        hidden.value = listbox.name;
    }
</script>
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    <asp:HiddenField ID="HiddenField1" runat="server" />
</asp:Content>


 

3.Code in content page(.vb):

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Me.Page.ClientScript.RegisterStartupScript(Me.[GetType](), "Ming", "GetNameOfListBox()", True)
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim listboxName As String = Me.HiddenField1.Value
        If Request(listboxName) IsNot Nothing Then
            Response.Write(Request(listboxName).ToString())
        End If
    End Sub


 

 

Hybird

But it doesn't seem to work if the listbox in inside of an update panel.

Please just modify the code(in content page) which I mentioned above:

1.Code in content page(.aspx):

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
    function GetNameOfListBox() {
        var listbox = document.getElementById("<%=ListBox1.ClientID %>");
        var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
        hidden.value = listbox.name;
    }
</script>
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <asp:HiddenField ID="HiddenField1" runat="server" />
    </ContentTemplate>
    </asp:UpdatePanel>

</asp:Content>


 

2.Code in content page(.vb):

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Me.Page.ClientScript.RegisterStartupScript(Me.[GetType](), "Ming", "GetNameOfListBox()", True)
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim listboxName As String = Me.HiddenField1.Value
        If Request(listboxName) IsNot Nothing Then
            'Show Result.
            Me.Label1.Text = Request(listboxName).ToString()
        End If
    End Sub


 

Hybird

I can use LINQ to get the either the .text of the list box items or the .value, but I don't know how to get both at the one time and return them into an array.

You can create an Entity class and pass the entity to an array as below:

Create a new page to demo the sample:

1.Code in page(.aspx):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


2.Code in page(.vb):

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Public list As New List(Of Items)()
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        For Each item As ListItem In Me.ListBox1.Items
            If item.Selected Then
                Dim i As New Items()
                i.ID = item.Value
                i.Text = item.Text
                list.Add(i)
            End If
        Next

        ' Now you can the value like this:
        For Each listitem As Items In list
            Response.Write(("Text:" + listitem.Text & " value:") + listitem.ID & "<br/>")
        Next
    End Sub


End Class

' Entity Class 
Public Class Items
    Private _id As String
    Private _text As String

    Public Property ID() As String
        Get
            Return _id
        End Get
        Set(ByVal value As String)
            _id = value
        End Set
    End Property
    Public Property Text() As String
        Get
            Return _text
        End Get
        Set(ByVal value As String)
            _text = value
        End Set
    End Property
End Class


Hope it can help you.

Wow, thank you Ming, that was an extremely informative post! Thanks for taking the time to actually create the test pages!

A note on some things I had to modify to get it working in case other people happen to stubble upon this informative post:

1.) in order to use the type datatable, at the top of your master page or content page you must include

<%@ Import Namespace="System.Data" %>

2.) I have a separate script content place holder where I generally place all of my scripts, and If I placed the

<script language="javascript" type="text/javascript">
          function GetNameOfListBox() {
              var listbox = document.getElementById("<%=ListBox1.ClientID %>");
              var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
              hidden.value = listbox.name;
          }  
 </script>

section of code in there it would not work. I had to place it in the same content place holder as the one where the hidden field is located.


Thanks again for your solution! Works wonders.

[RESOLVED] Url Routing in .net 4.0 and 3.5

Hello,

    I am trying to implement Url routing in 4.0 by following example http://www.dotnetspark.com/kb/2369-step-by-step-tutorial-on-url-routing-asp-net.aspx

Works fine..

Now the scenario is that i have gridview with object datasource which accepts  "Name" as query string.

<asp:gridview ID="Gridview1" runat="server" DataSourceID="ObjectDataSource1"></asp:gridview>
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
            OldValuesParameterFormatString="original_{0}" SelectMethod="Hello"
            TypeName="WebApplication2.Class.MethodsTest">
            <SelectParameters>
                <asp:QueryStringParameter Name="value" QueryStringField="Name" Type="String" />
            </SelectParameters>
        </asp:ObjectDataSource>

i tried this code. But i couldn't get the value in QueryString Field??

How to handle in this situation??

+

How to implement (the link example in net 3.5)??? because i don't  "

routes.MapPageRoute


" attribute in  3.5. i have few existing application in 3.5 so thought of implementing there too.


Please guide me..This example in Link looks very easy and simple to handle


Thanks....

if your getting the value parameter from a pageroute you cant use querystring you should use a Route Parameter something like this.

<asp:RouteParameter RouteKey="Name" Name="value" Type="String" />

here you have another example how to do it... http://weblogs.asp.net/hajan/archive/2010/10/15/url-routing-in-asp-net-4-0-web-forms.aspx

In his example he is showing a codebehind example of how to access the route but in my example show you how to use it...

Hope it helps....
 

So you mean to say that i can't use querystring for passing value to objectsource???

How to pass the value objectsource then???

In your link you have shown it in asp.net 3.5 sp1. right??

But how to pass value on click of the Button? like he has shown in the example (mine link).


because in my scenario i have to pass value through querystring in many places...so before i implement this feature i need to know how to access the value in pass it in objectdatasource and i don't want to use code behind.

i just checked on net http://weblogs.asp.net/scottgu/archive/2009/10/13/url-routing-with-asp-net-4-web-forms-vs-2010-and-net-4-0-series.aspx

Is the

<asp:routeparameter name="category" RouteKey="category" />

not available for 3.5 sp1 in webforms???

Thanks.




Im not sure if it works in 3.5 I upgraded all my apps to 4.0 when implementing routing. 

If you use url routing the routeparameter replaces querystring. the querystring fetches the parameter after the questionmark (?) in the url and when using routing you dont have it. 

 

i could see few example with routing stuff in asp.net 3.5 but i am not able to get  <asp:routeparameter in my html.



indeed this is why I choose to wait with moving from URL rewrite to URL routing until I moved to ASP.NET 4.0 even finding answers for URL Routing 4.0 is difficult if your not working with MVC and want some info covering more than the basic's

this works with ASP.NET 4.0 but if the <asp:routeparameter is not supported in asp.net 3.5 I can only see that you have to declare it in codebehind if you want it to work with you SqlDataSource.

 

ok i made one small application in 4.0 now and implemented Url routing in that and hosted in IIS in my machine (win 7).

but i get an error

HTTP Error 404.0 - Not Found

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

now what could be the reason...when i am running with my visual studio then it works fine but when i hosted in IIS then i landed in above problem.

code i use.

protected void Application_Start(object sender, EventArgs e)
        {
            CustomRouteTable(RouteTable.Routes);
        }


   void CustomRouteTable(RouteCollection routes)
        {
           

            routes.MapPageRoute("Telugu", "Movie/Telugu", "~/Telugu/Telugu.aspx");
        }

and in my default.aspx i kept a button on click of the button i wrote:

 protected void btnTelugu_Click(object sender, ImageClickEventArgs e)
        {
            Response.RedirectToRoute("Telugu");
        }


now where am i going wrong????

please guide me...


Hi,

abhishek0410

HTTP Error 404.0 - Not Found

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

 

It seems that IIS can not handle the UrlRoute when you enter the route url in browser.

I think you need to check the .NET framework version of the web site application pool. Url Route module need .NET 3.5 or upon.

Open the IIS manager and check it.

How to check the .NET version on IIS7:

http://www.west-wind.com/weblog/posts/289139.aspx

http://technet.microsoft.com/en-us/library/cc754523(WS.10).aspx

Or add the UrlRoutingModule in web.config:

Check this link:

http://msdn.microsoft.com/en-us/library/cc668202(v=vs.90).aspx

Hope this can help you.

Well do you have a file with the path ~/telugu/telugu.aspx because that is what you pointing at!

my guess would be that not...

 routes.MapPageRoute("Telugu", _ //routename

"Movie/Telugu", _  // you have hardcoded a virtual path and it is not expecting any paramenters parameter should be within {}

"~/Telugu/Telugu.aspx"); // this is the physical path...

--------------------------------------

let say you hav a file Movie.aspx in your root folder and you want to have a url that is movie / title .aspx it the route you should register is like this

routes.MapPageRoute("MovieRoute""Movie/{title}""~/Movie.aspx");

and then for the url to redirect correctly with a given parameter it should be something like this  

RedirectToAction("title", "Movie"); // Action, Controller
RedirectToRoute("MovieRoute"); // Route name or like this if it is to a route without a parameter

hope it helped a little

[RESOLVED] Can this button event be improved on

protected void btSearchDVR_Click(object sender, EventArgs e)
        {
            string add = txtAddress.Text;
            string city = txtCity.Text;
            string zip = txtZip.Text;
            string lnk = "http://www.site.com/sn/gpt.aspx?a" + HttpUtility.UrlEncode(add) + "&c=" + HttpUtility.UrlEncode(city) + "&z=" + HttpUtility.UrlEncode(zip);
            string results = null;


            try
            {
                WebClient client = new WebClient();
                results = client.DownloadString(lnk);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


            string[] coord = results.Split(new char[] { ',' });
            string txtLat = coord[0];
            string txtLon = coord[1];


            ViewState["MethodName"] = "SearchResults";


                ObjectDataSource1.SelectMethod = "SearchResults";
                ObjectDataSource1.SelectParameters.Clear();


                if ((searchValue.Text == "") || (searchValue.Text == " "))
                {
                    ObjectDataSource1.SelectParameters.Add("searchValue", TypeCode.String, null);
                }
                else
                {
                    ObjectDataSource1.SelectParameters.Add("searchValue", TypeCode.String, searchValue.Text);
                }
                if (ddlDVR.SelectedValue == "0")
                {
                    ObjectDataSource1.SelectParameters.Add("dvrName", TypeCode.String, null);
                }
                else
                {
                    ObjectDataSource1.SelectParameters.Add("dvrName", TypeCode.String, ddlDVR.SelectedValue);
                }
                if ((txtSdate.Text == "") || (txtSdate.Text == " "))
                {
                    ObjectDataSource1.SelectParameters.Add("sdate", TypeCode.String, null);
                }
                else
                {
                    ObjectDataSource1.SelectParameters.Add("sdate", TypeCode.String, txtSdate.Text);
                }
                if ((ddlSHH.SelectedValue == "00") && (ddlSMM.SelectedValue == "00") && (ddlSSS.SelectedValue == "00"))
                {
                    ObjectDataSource1.SelectParameters.Add("stime", TypeCode.String, null);
                }
                else
                {
                    ObjectDataSource1.SelectParameters.Add("stime", TypeCode.String, ddlSHH.SelectedValue + ":" + ddlSMM.SelectedValue + ":" + ddlSSS.SelectedValue);
                }
                if ((txtEdate.Text == "") || (txtEdate.Text == " "))
                {
                    ObjectDataSource1.SelectParameters.Add("edate", TypeCode.String, null);
                }
                else
                {
                    ObjectDataSource1.SelectParameters.Add("edate", TypeCode.String, txtEdate.Text);
                }
                if ((ddlEHH.SelectedValue == "00") && (ddlEMM.SelectedValue == "00") && (ddlESS.SelectedValue == "00"))
                {
                    ObjectDataSource1.SelectParameters.Add("etime", TypeCode.String, null);
                }
                else
                {
                    ObjectDataSource1.SelectParameters.Add("etime", TypeCode.String, ddlEHH.SelectedValue + ":" + ddlEMM.SelectedValue + ":" + ddlESS.SelectedValue);
                }


                if (ddlvidpri.SelectedValue == "00")
                {
                    ObjectDataSource1.SelectParameters.Add("vidpri", TypeCode.String, null);
                }
                else
                {
                    ObjectDataSource1.SelectParameters.Add("vidpri", TypeCode.Int32, ddlvidpri.SelectedValue);
                }
                if (results != "Not Found")
                {
                    ObjectDataSource1.SelectParameters.Add("videoRAD", TypeCode.Decimal, ddlRadius.SelectedValue);
                    ObjectDataSource1.SelectParameters.Add("videoLat", TypeCode.Double, txtLat);
                    ObjectDataSource1.SelectParameters.Add("videoLon", TypeCode.Double, txtLon);
                }


                Session["ObjectDataSource1"] = ObjectDataSource1;


                if (ddlView.SelectedValue == "LV")
                {
                    GridView3.Visible = true;
                    GridView3.DataBind();
                    DataList1.Visible = false;
                }
                if (ddlView.SelectedValue == "IV")
                {
                    DataList1.Visible = true;
                    DataList1.DataBind();
                    GridView3.Visible = false;
                }
                lblResults.Visible = true;
                GridView1.Visible = false;
                Session["btClick"] = "1";
                searchNav5.Visible = true;
                graphic.Visible = false;


                dac.insertauditintosql(dac.usn, "Data Search", searchValue.Text);


                if ((GridView3.Rows.Count == 0) || (DataList1.Items.Count == 0))
                {
                    ddlView.Visible = false;
                    Btn1.Visible = false;
                }
                else
                {
                    ddlView.Visible = true;
                    Btn1.Visible = true;
                }
        }


 

Wherever you are checking for blank text from a textbox, you can use either String.IsNullOrEmpty or String.IsNullOrWhiteSpace functions.

 

ObjectDataSource1.SelectParameters.Add("searchValue",TypeCode.String,String.IsNullOrWhiteSpace(searchValue.Text)?null:searchValue.Text);
ObjectDataSource1.SelectParameters.Add("dvrName",TypeCode.String,ddlDVR.SelectedValue== 0"?null:ddlDVR.SelectedValue);
ObjectDataSource1.SelectParameters.Add("sdate",TypeCode.String,String.IsNullOrWhiteSpace(txtSdate.Text)?null:txtSdate.Text);
ObjectDataSource1.SelectParameters.Add("edate",TypeCode.String,String.IsNullOrWhiteSpace(txtEdate.Text)?null:txtEdate.Text);

 

 

[RESOLVED] Gwtting values from dynamic fields

Hello, anyone know of anyway to get the value of this dynamic data? I've been very stress trying to get the value of this fields. but I dont know how should I code upon the submit button to get the dynamic value, I'm doing a 3 tier, with dataset XSD, using can anyone advise me what to do?

By the way, its a button to generate the dynamic fields, and each dynamic fields id is "dynamic field name" + i, so please kindly go through the codes and give me a solution~ its urgent! thanks in advance!

Its quite long though :x

protected void btnGen_Click(object sender, EventArgs e)
    {

        for (int i = 0; i < Convert.ToInt32(tbNum.Text); i++)
        {

            // label and textbox needed
            Label lblSch = new Label();
            TextBox tbSch = new TextBox();
            Label lblWsGrp = new Label();
            DropDownList ddlWsGrp = new DropDownList();
            RadioButtonList rblTra = new RadioButtonList();
            Label lblSTime = new Label();
            Label lblETime = new Label();
            TextBox tbSTime = new TextBox();
            TextBox tbETime = new TextBox();
            Label lblstar = new Label();
            Label space = new Label();
            space.Text = " ";
            Label lbltime = new Label();
            lbltime.Text = "-example format:08:00/13:15-";
            Label lbltime2 = new Label();
            lbltime2.Text = "-example format:08:00/13:15-";
           

            //calendar control for sess date
            AjaxControlToolkit.CalendarExtender CeSess = new AjaxControlToolkit.CalendarExtender();
            CeSess.ID = "SessDate" + i;
            CeSess.Format = "dd/MM/yyyy";
            CeSess.TargetControlID = "tbSch" + i;
            CeSess.TodaysDateFormat = "dd/MM/yyyy";
            CeSess.Enabled = true;
            CeSess.CssClass = "cal_Theme1";
            CeSess.EnableViewState = true;

           //sess date
            lblSch.ID = "lblSch" + i;
            lblSch.Text = "Session Date : ";
            lblSch.EnableViewState = true;

            tbSch.ID = "tbSch" + i;
            tbSch.Width = 210;
            tbSch.Height = 27;
            tbSch.EnableViewState = true;

            //workshop grp
            lblWsGrp.ID = "lblwsgrp" + i;
            lblWsGrp.Text = "Workshop Group : ";
            lblWsGrp.EnableViewState = true;

            ObjectDataSource obddl = new ObjectDataSource();
            obddl.ID = "obddl" + i;
            obddl.TypeName = "BusinessLogic.RegBLL";
            obddl.SelectMethod = "GetAllReg";
            obddl.DataBind();

            ddlWsGrp.ID = "ddlWsGrp" + i;
            ddlWsGrp.Height = 27;
            ddlWsGrp.Width = 210;
            ddlWsGrp.Items.Add("1");
            ddlWsGrp.Items.Add("2");
            //ddlWsGrp.DataSourceID = obddl.ID;
            //ddlWsGrp.AppendDataBoundItems = true;
            //ddlWsGrp.DataTextField.Equals("wsGrp");
           // ddlWsGrp.DataValueField.Equals("regID");
            ddlWsGrp.EnableViewState = true;

            //Start Time
            lblSTime.ID = "ST" + i;
            lblSTime.Text = "Start Time : ";
            lblSTime.EnableViewState = true;

            tbSTime.ID = "strt" + i;
            tbSTime.Width = 210;
            tbSTime.Height = 27;
            tbSTime.EnableViewState = true;

            //End Time
            lblETime.ID = "ET" + i;
            lblETime.Text = "End Time : ";
            lblETime.EnableViewState = true;

            tbETime.ID = "endt" + i;
            tbETime.Width = 210;
            tbETime.Height = 27;
            tbETime.EnableViewState = true;           
           

            //table to store data
            TableRow trow = new TableRow();
            TableRow trow2 = new TableRow();
            TableRow trow3 = new TableRow();
          

            //row1
            TableCell tc1 = new TableCell();
            TableCell tc2 = new TableCell();
            TableCell tc3 = new TableCell();
            TableCell tc4 = new TableCell();
            TableCell tc45 = new TableCell();
            //row2
            TableCell tc25 = new TableCell();
            TableCell tc26 = new TableCell();
            TableCell tc27 = new TableCell();
            TableCell tc28 = new TableCell();
            //row3
            TableCell tc29 = new TableCell();
            TableCell tc30 = new TableCell();
            TableCell tc31 = new TableCell();
            TableCell tc32 = new TableCell();           

            tc1.Controls.Add(lblSch);
            tc2.Controls.Add(tbSch);
            tc3.Controls.Add(lblWsGrp);
            tc4.Controls.Add(ddlWsGrp);
            tc45.Controls.Add(space);

           tc25.Controls.Add(lblSTime);
            tc26.Controls.Add(tbSTime);
            tc27.Controls.Add(lblETime);
            tc28.Controls.Add(tbETime);

            tc29.Controls.Add(space);
            tc30.Controls.Add(lbltime);
            tc31.Controls.Add(space);
            tc32.Controls.Add(lbltime2);

          trow.Cells.Add(tc1);
            trow.Cells.Add(tc2);
            trow.Cells.Add(tc3);
            trow.Cells.Add(tc4);
            trow.Cells.Add(tc45);
             trow2.Cells.Add(tc26);
            trow2.Cells.Add(tc27);
            trow2.Cells.Add(tc28);
            trow3.Cells.Add(tc29);
            trow3.Cells.Add(tc30);
            trow3.Cells.Add(tc31);
            trow3.Cells.Add(tc32);

            this.table3.Rows.Add(trow);
            this.table3.Rows.Add(trow2);
            this.table3.Rows.Add(trow3);
        }
    }

 

 

 

I think you can create a loop on your table rows then a nested loop with the cells , if you're using foreach you wont need the id.

Hi there, thanks for replying,

Do you have an example which i can refer to? thanks :) 

I dont have exact code but it's something like this :

foreach (
TableRow
x in Table1.Rows)
{

     

foreach (
TableCell y 
 in 
TableRow.Cells
)
    {

             foreach(Control ctrl in y .Controls)
              {
               }

       }

    }

}


Hi, am i right to declare it this way? because i need to get the values from 4 fields, namely 3 textboxes and from 1 dropdownlist :), and then to pass it to insert into my database :)

foreach (TableRow row in table3.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                    foreach (Control c in cell.Controls)
                    {
                        for(int r= 0 ; r <cell.Controls.Count; r++)
                        {
                          
                            if(c.GetType() == typeof(TextBox))
                            {
                                if((c.ID.Contains("tbSch")))
                                {
                                    TextBox tbSch = c as TextBox;
                                    string sessDate = tbSch.Text;
                                }
                                else if ((c.ID.Contains("strt")))
                                {
                                    TextBox tbST = c as TextBox;
                                    string sTime = tbST.Text;
                                }
                                else if ((c.ID.Contains("endt")))
                                {
                                    TextBox tbET = c as TextBox;
                                    string sTime = tbET.Text;
                                }
                         
                            }
                            else if (c.GetType() == typeof(DropDownList))
                            {
                                DropDownList ddlWs = c as DropDownList;
                                string wsGrp = ddlWs.SelectedValue.ToString();
                            }
                        }
                    }
                }
            }

foreach (TableRow row in table3.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                    foreach (Control c in cell.Controls)
                    {
                            if(c.GetType() == typeof(TextBox))
                            {
                                if((c.ID.Contains("tbSch")))
                                {
                                    TextBox tbSch = c as TextBox;
                                    string sessDate = tbSch.Text;
                                }
                                else if ((c.ID.Contains("strt")))
                                {
                                    TextBox tbST = c as TextBox;
                                    string sTime = tbST.Text;
                                }
                                else if ((c.ID.Contains("endt")))
                                {
                                    TextBox tbET = c as TextBox;
                                    string sTime = tbET.Text;
                                }
                         
                            }
                            else if (c.GetType() == typeof(DropDownList))
                            {
                                DropDownList ddlWs = c as DropDownList;
                                string wsGrp = ddlWs.SelectedValue.ToString();
                            }
                    
                    }
                }
            }


you're having an extra loop you're already looping on controls so no need for the last nested for , else than this I guess you're right .



Hey, thanks for the reply, I tried debugging, but I cannot seem to see the value, lol so im not sure whether its containing values :) 

Hi,

According to your code and description ,I would like to suggest you to check the link below for the similar thread which provides some solutions for the same issue.

http://forums.asp.net/p/1646901/4281893.aspx

Hope this helps.

[RESOLVED] control validation appears in disorder

I

I´m using different validation controls from asp.net in a page that has like 10 controls.  When I click on insert validation occurs but my problem is that error messages appear in summary for some and other validation only takes place when I correct the first errors which is very confusing.  I´m trying to get all validation messages to be shown all at once but for some reason not all of them happen at the same time.

 

<InsertItemTemplate>
                        <table>
                            <tr>
                                <td>
                                    <asp:Label ID="lblContrato" runat="server" Text="Contrato"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewContrato" runat="server" Text='<%# Bind("contnume") %>'></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtNewContrato"
                                        ErrorMessage="Contrato debe ser un numero" ValidationExpression="\d+">*</asp:RegularExpressionValidator>
                                    <ajaxToolkit:ValidatorCalloutExtender ID="RegularExpressionValidator1_ValidatorCalloutExtender"
                                        runat="server" Enabled="True" TargetControlID="RegularExpressionValidator1">
                                    </ajaxToolkit:ValidatorCalloutExtender>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                                        ControlToValidate="txtNewContrato" ErrorMessage="Contrato es requerido">*</asp:RequiredFieldValidator>
                                </td>
                                <td>
                                    <asp:Label ID="lblPersona" runat="server" Text="Persona"></asp:Label>
                                </td>
                                <td>
                         <%--<asp:DropDownList ID="DdPersona" runat="server" DataSourceID="OdsPersona"
                            DataTextField="nomCompleto" DataValueField="persnume"
                            SelectedValue='<%# Bind("persnume") %>' Font-Size="Small">
                        </asp:DropDownList>--%>
                         <%--<ajaxToolkit:DropDownExtender ID="DdPersona_DropDownExtender" runat="server"
                             DynamicServicePath="" Enabled="True" TargetControlID="DdPersona">
                         </ajaxToolkit:DropDownExtender>--%>
                        <asp:ObjectDataSource ID="OdsPersona" runat="server" SelectMethod="GetPersonaWithID"
                            TypeName="Facturacion.DAL.PersonaDataLayer" >
                            <SelectParameters>
                            <asp:Parameter DefaultValue="6" Name="tipenume" Type="Int16" />
                             </SelectParameters>
                            </asp:ObjectDataSource>
                            <ajaxToolkit:ComboBox ID="cmbPersona" runat="server"
                             AutoCompleteMode="Suggest" DataSourceID="OdsPersona"
                             DataTextField="nomCompleto" DataValueField="persnume" Text='<%# Bind("persnume") %>'
                             DropDownStyle="DropDownList" MaxLength="0" style="display: inline;"
                             AppendDataBoundItems="True" TabIndex="1">
                                <asp:ListItem Selected="True" Value="0">Seleccione persona</asp:ListItem>
                         </ajaxToolkit:ComboBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
                                        ControlToValidate="cmbPersona" ErrorMessage="Persona es requerido"
                                        InitialValue="0">*</asp:RequiredFieldValidator>
                            </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblFechaRegistro" runat="server" Text="Fecha de Registro"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewFechaRegistro" runat="server" Text="<%# System.DateTime.Now.ToString() %>"
                                        ReadOnly="True" TabIndex="8"></asp:TextBox>
                                </td>
                                <td>
                                    <asp:Label ID="lblFechaLegalizacion" runat="server" Text="Fecha de Legalizacion"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewFechaLegalizaion" runat="server"
                                        Text='<%# Bind("contfele") %>' TabIndex="2"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
                                        ControlToValidate="txtNewFechaLegalizaion"
                                        ErrorMessage="Fecha de Legalizacion es requerido">*</asp:RequiredFieldValidator>
                                    <ajaxToolkit:CalendarExtender ID="txtNewFechaRegistro_CalendarExtender" runat="server"
                                        Enabled="True" TargetControlID="txtNewFechaLegalizaion" Format="dd/MM/yyyy" TodaysDateFormat="dd/MM/yyyy">
                                    </ajaxToolkit:CalendarExtender>
                                    <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
                                        ControlToValidate="txtNewFechaLegalizaion"
                                        ErrorMessage="Error en formato de fecha dd-mm-yyyy"
                                        ValidationExpression="^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$"></asp:RegularExpressionValidator>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblVendedor" runat="server" Text="Vendedor"></asp:Label>
                                </td>
                                <td>
                                    <asp:DropDownList ID="ddlVendedor" runat="server" DataSourceID="OdsVendedor" DataTextField="nomVendedor"
                                        DataValueField="vendnume" SelectedValue='<%# Bind("vendnume") %>' Font-Size="Small"
                                        AppendDataBoundItems="True" TabIndex="12">
                                        <asp:ListItem Selected="True" Value="0">Seleccione Vendedor</asp:ListItem>
                                    </asp:DropDownList>
                                    <asp:ObjectDataSource ID="odsVendedor" runat="server" SelectMethod="GetVendedores"
                                        TypeName="Facturacion.DAL.VendedorDataLayer"></asp:ObjectDataSource>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
                                        ControlToValidate="ddlVendedor" ErrorMessage="Vendedor es requerido"
                                        InitialValue="0">*</asp:RequiredFieldValidator>
                                </td>
                                <td>
                                    <asp:Label ID="lblPrograma" runat="server" Text="Programa"></asp:Label>
                                </td>
                                <td>
                                    <asp:DropDownList ID="ddlPrograma" runat="server" DataSourceID="odsPrograma" DataTextField="prognomb"
                                        DataValueField="prognume" SelectedValue='<%# Bind("prognume") %>' Font-Size="Small"
                                        AppendDataBoundItems="True">
                                        <asp:ListItem Selected="0">Seleccione Programa</asp:ListItem>
                                    </asp:DropDownList>
                                    <asp:ObjectDataSource ID="odsPrograma" runat="server" SelectMethod="GetProgramas"
                                        TypeName="Facturacion.DAL.ProgramaDataLayer"></asp:ObjectDataSource>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
                                        ControlToValidate="ddlPrograma" ErrorMessage="Programa es requerido"
                                        InitialValue="0">*</asp:RequiredFieldValidator>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblEmpresa" runat="server" Text="Empresa"></asp:Label>
                                </td>
                                <td>
                                    <input type="text" value="<%=Session["nomEmpresa"]%>" name="txtNewEmpresa" readonly="readonly">
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblNombreRef1" runat="server" Text="Nombre Ref1"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewNombreRef1" runat="server" Text='<%# Bind("contr1no") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
                                        ControlToValidate="txtNewNombreRef1"
                                        ErrorMessage="Nombre referencia 1 es requerido">*</asp:RequiredFieldValidator>
                                </td>
                                <td>
                                    <asp:Label ID="lblApellidoRef1" runat="server" Text="Apellido Ref1"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewApellidoRef1" runat="server" Text='<%# Bind("contr1ap") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server"
                                        ControlToValidate="txtNewApellidoRef1"
                                        ErrorMessage="Apellido referencia1 es requerido">*</asp:RequiredFieldValidator>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblTelefonoRef1" runat="server" Text="Telefono Ref1"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewTelefonoRef1" runat="server" Text='<%# Bind("contr1te") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server"
                                        ControlToValidate="txtNewTelefonoRef1"
                                        ErrorMessage="Telefono referencia1 es requerido">*</asp:RequiredFieldValidator>
                                    <asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server"
                                        ControlToValidate="txtNewTelefonoRef1"
                                        ErrorMessage="Telefono Referencia1 debe ser un numero"
                                        ValidationExpression="\d+">*</asp:RegularExpressionValidator>
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblNombreRef2" runat="server" Text="Nombre Ref2"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewNombreRef2" runat="server" Text='<%# Bind("contr2no") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server"
                                        ControlToValidate="txtNewNombreRef2"
                                        ErrorMessage="Nombre Referencia2 es requerido">*</asp:RequiredFieldValidator>
                                </td>
                                <td>
                                    <asp:Label ID="lblApellidoRef2" runat="server" Text="Apellido Ref2"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewApellidoRef2" runat="server" Text='<%# Bind("contr2ap") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server"
                                        ControlToValidate="txtNewApellidoRef2"
                                        ErrorMessage="Apellido Referencia2 es requerido">*</asp:RequiredFieldValidator>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblTelefonoRef2" runat="server" Text="Telefono Ref2"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewTelefonoRef2" runat="server" Text='<%# Bind("contr2te") %>'></asp:TextBox>
                                </td>
                                <td>
                                    <asp:Label ID="lblAnulado" runat="server" Text="Anulado"></asp:Label>
                                </td>
                                <td>
                                    <asp:RadioButtonList ID="RadioButtonList2" runat="server" RepeatDirection="Horizontal"
                                        SelectedValue='<%# Bind("contanul") %>'>
                                        <asp:ListItem Value="S">Si</asp:ListItem>
                                        <asp:ListItem Value="N">No</asp:ListItem>
                                    </asp:RadioButtonList>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblObservacion" runat="server" Text="Observaciones"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewTelefonoRef3" runat="server" Rows="5" Text='<%# Bind("contobse") %>'
                                        TextMode="MultiLine"></asp:TextBox>
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                            </tr>
                        </table>
                        <asp:ValidationSummary ID="ValidationSummary2" runat="server" />
                        <br />
                        <asp:LinkButton ID="btnInsertar" runat="server" CommandName="Insert"
                            TabIndex="13">Insertar</asp:LinkButton>
                        <asp:LinkButton ID="lnkCancelar" runat="server" CommandName="Cancel"
                            TabIndex="14">Cancelar</asp:LinkButton>
                    </InsertItemTemplate>

 

I tried to figure out a solution by assigning ordered tab index, but behaviour keeps the same.  Some controls appear to be validated first with their respective error messages whereas others are validated after the firts ones.

 

thanks in advance.

edotom

Is there any rhyme or reason to which validation messages show?  (ie: do all of the required field validators show first and then the regex validators?)  "If the input control is empty, no validation functions are called and validation succeeds." (from http://msdn.microsoft.com/en-us/library/eahwtc9e.aspx).

Otherwise, take a look to see if some of the validation is occuring on the server instead of the client.  This may also cause the behavior.

The part that is not validated with the other controls is this:

<asp:ObjectDataSource ID="OdsPersona" runat="server" SelectMethod="GetPersonaWithID"
                            TypeName="Facturacion.DAL.PersonaDataLayer" >
                            <SelectParameters>
                            <asp:Parameter DefaultValue="6" Name="tipenume" Type="Int16" />
                             </SelectParameters>
                            </asp:ObjectDataSource>
                            <ajaxToolkit:ComboBox ID="cmbPersona" runat="server"  
                             AutoCompleteMode="Suggest" DataSourceID="OdsPersona"
                             DataTextField="nomCompleto" DataValueField="persnume" Text='<%# Bind("persnume") %>'
                             DropDownStyle="DropDownList" MaxLength="0" style="display: inline;"
                             AppendDataBoundItems="True" TabIndex="1">
                                <asp:ListItem Selected="True" Value="0">Seleccione persona</asp:ListItem>
                         </ajaxToolkit:ComboBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
                                        ControlToValidate="cmbPersona" ErrorMessage="Persona es requerido"
                                        InitialValue="0">*</asp:RequiredFieldValidator>

All other controls are validated first and when all that is done then this part is validated.  The difference is that its an ajaxtoolkit:combobox.
how can I get that control validated altogether with the others?

I don't think the validator supports the ajaxcontroltoolkit's ComboBox control.  There might be some server-side support (which is probably what you see on the second try), but I wouldn't count on it.  You might have to investigate a making a CustomValidator.

...or try this on for size: http://ajaxcontroltoolkit.codeplex.com/workitem/24417

It is a hack, but it looks like something that might just work.