Category Archives: Linq

[RESOLVED] Converting a string to a number

I want to convert a string to a number.
But some strings have a normal char in it like:    543p  
How can delete all chars, instead of all chars that are normal in a decimal ?

Jelmer850i

How can delete all chars, instead of all chars that are normal in a decimal ?

You can filter out special characters and other alphabets using Int.TryParse method

using System.Linq;
string input = "45234&^&#@$^*367213p";
int number = 0;
input = string.Join("", input.ToCharArray().Where(a => Int32.TryParse(a.ToString(), out number)));

[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.

Accessing Database from Silverlight

Hi All,

I am working on Silverlight 2 Beta 2. I ma trying to bind the data to a DataGrid from the DB using LINQ. When I search in the net all articles are talking about binding the data using WCF Service only.

Without WCF we cannot bind the Data?

 I want to design a DataGrid like below


___________________________________________________
|               |                |               Number of                               |
|               |                |___________________________________|
|Column1  |Column 2 |SubColumn1|SubColumn2|SubColumn3|
|________|________ |__________|__________|____________|
| 1          |  a          | as            | fg             | gh            |
| 2          |  b          | sd            | fg             | fgh           |
| 3          |  c          | df             | fg             | fgf           |
________________________________________________

Total     | Total of this Col | same | same...

Let me know

Thanks

Anandraj.A.

You have only 2 method to bind grid in the silver light 1). WCF and 2). Web service (asmx).
1. Create Interface for Datagrid(classes, methods)
2. Create User Control as a Label
3. You have to design a datagrid as your wish by the user control or any.
4. Place table-data into the Label-User-Control through WCF

Note: Dropdown also possible by User Control


 Hi Anandraj

it is a little tricky at best to get databinding in silverlight,  take a look at these videos should help. ado.net data services made life a little easier (but not much) seems to be the way to go.but im not sure if it works with beta, any reason you are using beta?

http://www.microsoft.com/uk/msdn/screencasts/screencast/308/adonet-data-services-a-basic-silverlight-client.aspx

Im not sure about doing it with silverlight 2 beta either?, I know the datagrid changed at some point from beta to live (i think anyway) so you may hit a problem with that.

Hi anand,

WCF is the most suitable way to bind the data in Silverlight applications. We can use LINQ TO SQL classes to create the data layer mapped over SQL Server tables. Further by creating Silverlight-enabled-WebService we can access above created LINQ classes to access the data and fetching to Silverlight application.

First create a silverlight application.

Secondly,

Now that you have created the Silverlight 3 Application, we would add a LINQ to SQL file that is *.dbml .

LinqToSQLSilverlight2.gif


Thirdly,

To communicate with LINQ to SQL we need to have a service that client can call at any time.

Add Silverlight enabled WCF Service to the Web Project.

LinqToSQLSilverlight7.gif


In the Service.svc.cs add methods as per your requirement.

I have written two methods such as:


#region [GetAllEmployees]


        [OperationContract]
        List<vw_mst_EmployeeDetail> GetAllEmployees()
        {
            using (EmployeeDBDataContext context = new EmployeeDBDataContext())
            {
                var result = from emp in context.vw_mst_EmployeeDetails
                             select emp;


                return result.ToList();
            }
        }


        #endregion


        #region [GetEmployeesByFirstName]


        [OperationContract]
        List<vw_mst_EmployeeDetail> GetEmployeesByFirstName(string firstName)
        {
            using (EmployeeDBDataContext context = new EmployeeDBDataContext())
            {
                var result = from emp in context.vw_mst_EmployeeDetails
                             where emp.FirstName.StartsWith(firstName)
                             select emp;


                return result.ToList();
            }
        }


        #endregion


Fourthly,

After writing the service build the project and get this service's reference in Silverlight 3 Project as shown in below figure.

LinqToSQLSilverlight10.gif


<div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        #region [GetAllEmployees]</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        [OperationContract]</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        List<vw_mst_EmployeeDetail> GetAllEmployees()</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        {</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            using (EmployeeDBDataContext context = new EmployeeDBDataContext())</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            {</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                var result = from emp in context.vw_mst_EmployeeDetails</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                             select emp;</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                return result.ToList();</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            }</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        }</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        #endregion</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        #region [GetEmployeesByFirstName]</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        [OperationContract]</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        List<vw_mst_EmployeeDetail> GetEmployeesByFirstName(string firstName)</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        {</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            using (EmployeeDBDataContext context = new EmployeeDBDataContext())</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            {</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                var result = from emp in context.vw_mst_EmployeeDetails</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                             where emp.FirstName.StartsWith(firstName)</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                             select emp;</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                return result.ToList();</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            }</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        }</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        #endregion</div>

After you add the service it would create the ServiceReferences.ClientConfig file.

Now it's time to design our Silverlight UI in Blend, I have gone for a simple approach, where simple buttons and textbox would help us getting the result which would be displayed in DataGrid.


LinqToSQLSilverlight11.gif


XAML for your reference is as follows - 


<UserControl

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 

    mc:Ignorable="d" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="Mazeweb.Silverlight.MainPage"

    d:DesignWidth="640" d:DesignHeight="480">

    <Grid x:Name="LayoutRoot">

     <Grid.Background>

     <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

     <GradientStop Color="#FFF2F2F8" Offset="0.948"/>

     <GradientStop Color="#FF5B99F2" Offset="0.665"/>

     </LinearGradientBrush>

     </Grid.Background>

     <Grid.RowDefinitions>

     <RowDefinition Height="0.106*"/>

     <RowDefinition Height="0.056*"/>

     <RowDefinition Height="0.838*"/>

     </Grid.RowDefinitions>

        <TextBlock HorizontalAlignment="Center" Text="LINQ TO SQL &amp; SILVERLIGHT 3" 

             TextWrapping="Wrap" FontSize="21.333" TextDecorations="Underline" Margin="0,3,0,19" d:LayoutOverrides="Height"/>

        <StackPanel Margin="0" Height="80" VerticalAlignment="Center" Orientation="Horizontal" 

                    HorizontalAlignment="Center" Grid.Row="1">

            <Button x:Name="btnAll" Height="25" Content="Show All" Click="btnAll_Click" VerticalAlignment="Center" Margin="0,0,0,8" Width="109" />

            <Rectangle Height="25" Width="10"/>

            <TextBox x:Name="txtName" Height="25" TextWrapping="Wrap" Width="164" VerticalAlignment="Center"/>

            <Rectangle Height="25" Width="10"/>

            <Button x:Name="btnSubmit" Height="25" Content="Search" Click="btnSubmit_Click" VerticalAlignment="Center" Margin="0,0,0,8" Width="109" />

        </StackPanel>

        <data:DataGrid x:Name="dgResults" Margin="8,10,8,89" Grid.Row="2" IsReadOnly="True" 

                       AutoGenerateColumns="False">

            <data:DataGrid.Columns>

                <data:DataGridTextColumn Binding="{Binding ID}" Header="ID"></data:DataGridTextColumn>

                <data:DataGridTextColumn Binding="{Binding FirstName}" Header="First Name"></data:DataGridTextColumn>

                <data:DataGridTextColumn Binding="{Binding LastName}" Header="Last Name"></data:DataGridTextColumn>

                <data:DataGridTextColumn Binding="{Binding UserCode}" Header="EmailID"></data:DataGridTextColumn>

                <data:DataGridTextColumn Binding="{Binding DesignationName}" Header="Designation"></data:DataGridTextColumn>

                <data:DataGridTextColumn Binding="{Binding BranchName}" Header="Branch"></data:DataGridTextColumn>

            </data:DataGrid.Columns>

        </data:DataGrid>

    </Grid>

</UserControl>

<div>
</div><div>
</div><div>Finally,</div><div>
</div><div>Now we would write client side code to call the service and display the result.

Following code is for Show All Button Click and displaying the result.
</div><div>
</div><div><div>        private void btnSubmit_Click(object sender, RoutedEventArgs e)</div><div>        {</div><div>            ServiceClient clientService = new ServiceClient();</div><div>            clientService.GetEmployeesByFirstNameCompleted += new EventHandler<GetEmployeesByFirstNameCompletedEventArgs>(clientService_GetEmployeesByFirstNameCompleted);</div><div>            clientService.GetEmployeesByFirstNameAsync(txtName.Text);</div><div>        }</div><div>
</div><div>        void clientService_GetEmployeesByFirstNameCompleted(object sender, GetEmployeesByFirstNameCompletedEventArgs e)</div><div>        {</div><div>            dgResults.ItemsSource = e.Result;</div><div>        }</div><div>
</div><div>        private void btnAll_Click(object sender, RoutedEventArgs e)</div><div>        {</div><div>            ServiceClient clientService = new ServiceClient();</div><div>            clientService.GetAllEmployeesCompleted += new EventHandler<GetAllEmployeesCompletedEventArgs>(clientService_GetAllEmployeesCompleted);</div><div>            clientService.GetAllEmployeesAsync();</div><div>        }</div><div>
</div><div>        void clientService_GetAllEmployeesCompleted(object sender, GetAllEmployeesCompletedEventArgs e)</div><div>        {</div><div>            dgResults.ItemsSource = e.Result;</div><div>        }</div><div>
</div><div>
</div><div>Now, Finally you can test your application successfully running.</div>
</div>


Hope this POST helps.


I wrote an article about connecting a datagrid to a silverlight project here. Perhaps it will be useful.

Hi Dear

You have three option

1: Linq to Sql server

2. WCF Service

3. Web Service

[RESOLVED] c# include code problem

Hello,


I am new in asp.net and c#. I am good at php and understands the logic. But i have no idea what is error in this.

when I just include one line ' using System;' it shows error. I also tried c# page putting codebeign and calll it but still same error.

Here is my test html page and action c# page

http://marinerorubio.com/form.aspx

<body>
<form action="test.aspx" method="post">
<input type="submit" name="Submit" value="Submit" />
</form>


Action Page


<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="iso-8859-1" %>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>


<script runat="server">

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Centricom.POLi.Merchant.Sample.HostedPageDemo
{
public partial class CheckoutNonSecure : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String parameters = String.Empty;
String url = String.Empty;
if (!IsPostBack)
{
txtMerchantRefNumber.Text = "TRN0001"; // your unique transaction ref #
txtMerchantData.Text = "Gladiator"; // your additional information
txtAmount.Text = "19.99"; // your payment amount
txtDateTime.Text = DateTime.Now.ToString(); // your transaction timestamp
parameters =
String.Format("authenticationcode={0}&merchantrefnumber={1}&amount={2}&merchantdata={3}&dateti
me={4}",
"MyPassword", txtMerchantRefNumber.Text, txtAmount.Text,
txtMerchantData.Text, txtDateTime.Text);
url =
String.Format("http://hosted.dev.agilitytx.com/Default.aspx?merchantcode={0}&secure={1}&erroru
rl={2}&{3}",
"PriceBusterDVD_AU", // your merchant code
"false", // non-secure transmission
"www.yourserver.com/Error.aspx", // your error URL
String.Format("{0}", parameters)); // unencrypted payment data
Response.Redirect(url);
}
}
}
}

</script>
</body>
</html>


in action page even I write 


<script runat="server">

using System;

</script>


I can see same error.


Please help.


Thanks in advance.

Instead of using using system; in the code...

you got to use something like this...

<div style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"><%@ Import Namespace="System" %></div> <div style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"><%@ Import Namespace="System.IO" %></div>

<%@ Import Namespace="System" %>

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

....

and place that code in the top of page after @PAge directive....

Thanks.