Navigation

Search

Categories

On this page

Dynamic SQL
I Miss Include Files
Highlighting a Selected Checkbox Item
Using the CommandName Property
test
How to Draw Homer Simpson
Using jQuery to Limit the Number of Characters in a Multiline Textbox

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 240
This Year: 46
This Month: 3
This Week: 0
Comments: 0

Sign In
Pick a theme:

# Tuesday, October 20, 2009
Tuesday, October 20, 2009 6:54:57 PM (GMT Daylight Time, UTC+01:00) ( SQL )


http://www.sommarskog.se/dyn-search-2005.html#sp_executesql

I create a lot of search forms and I’ve always just used in-line SQL by examining each form element value and then building a SQL string to run against a view or table.  This article discusses how to build a stored procedure in SQL Server 2005 or 2008 using the system stored procedure, sp_executesql.

Here is my example

CREATE PROCEDURE [dbo].[p_Search]

    @id_field int = NULL,
    @FieldName varchar(300) = NULL,
    @TableName varchar(250) = NULL,
    @FieldType varchar(3000) = NULL,
    @DataEntry varchar(250) = NULL                  
                   
AS                                                                    
DECLARE @sql  nvarchar(max),
    @paramlist  nvarchar(4000)                                 
                                     
SELECT @sql =                                                  
    'SELECT * FROM v_FieldDetail          
     WHERE  1 = 1'                                                 
                                                                   
IF @id_field IS NOT NULL                                            
   SELECT @sql = @sql + ' AND id_field = @xid_field'           
                                                                   
IF @FieldName IS NOT NULL                                           
   SELECT @sql = @sql + ' AND FieldName LIKE + ''%'' + @xFieldName + ''%'''            

IF @TableName IS NOT NULL                                           
   SELECT @sql = @sql + ' AND TableName LIKE + ''%'' + @xTableName + ''%''' 
--This one utilizes a split function (below) to accept a comma-delimited string for use with an IN clause
IF @FieldType IS NOT NULL                                           
    SELECT @sql = @sql + ' AND FieldType IN ( SELECT * from dbo.Split( @xFieldType, '',''))'
IF @DataEntry IS NOT NULL                                           
   SELECT @sql = @sql + ' AND DataEntry LIKE + ''%'' + @xDataEntry + ''%'''
                                                                  
   SELECT @sql = @sql + ' ORDER BY FieldName'
    

--PRINT @sql

SELECT @paramlist =                      
      '@xid_field int,
      @xFieldName varchar(300), 
     @xTableName varchar(250),
    @xFieldType varchar(3000),
    @xDataEntry varchar(250)                       
                                                                   
EXEC sp_executesql @sql, @paramlist,@id_field,
    @FieldName,
    @TableName,
    @FieldType,
    @DataEntry
            
                                      
To call this stored procedure and bind the results to a Gridview, do something like this:
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs)       

        Dim ds As DataSet           
        Dim strSql As String = "p_Search"
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conString_FieldInventory").ConnectionString)
        
        Dim cmd As New SqlCommand(strSql, con)
        cmd.CommandType = CommandType.StoredProcedure
        
           'p_Search uses dynamic SQL so we pass a value to it only when there is one
           If lblid_field2Text <> "" Then
               cmd.Parameters.Add("@id_field", SqlDbType.Int).Value = Convert.ToInt32(lblid_field.Text)        
        End If
        
        If txtFieldName.Text <> "" Then
            cmd.Parameters.Add("@FieldName", SqlDbType.VarChar).Value = txtFieldName.Text
        End If
        
        If txtTableName.Text <> "" Then
            cmd.Parameters.Add("@TableName", SqlDbType.VarChar).Value = txtTableName.Text
        End If
   
        ‘This one passes a comma-delimited string for @FieldType which is used in the split function
        If ddlFieldType.SelectedValue <> "" Then
            Dim strSearchValue As String = ""
            Dim li As ListItem
            For Each li In ddlFieldType.Items
                If li.Selected = True Then
                    strSearchValue = strSearchValue & li.Value & "#"
                End If
            Next
            strSearchValue = Left(strSearchValue, (Len(strSearchValue) - 1))
            strSearchValue = Replace(strSearchValue, "#", ",")
            cmd.Parameters.AddWithValue("@FieldType", SqlDbType.VarChar).Value = strSearchValue
        End If
        
        If txtDataEntry.Text <> "" Then
            cmd.Parameters.Add("@DataEntry", SqlDbType.VarChar).Value = txtDataEntry.Text
        End If         
        
        Try
            con.Open()
            Dim MyAdapter As New SqlDataAdapter(cmd) 
            
            ds = New DataSet()
            MyAdapter.Fill(ds, "Requests")
              
            Dim intRecordCount As Integer = ds.Tables(0).Rows.Count() 
            lblRowCount.Text = "Your search returned " & intRecordCount & " records"
            
            GridView1.DataSource = ds.Tables("Requests").DefaultView
            GridView1.DataBind()
        Finally
            con.Close()
        End Try        
    End Sub

--Split function

CREATE FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))     
returns @temptable TABLE (items varchar(8000))     
as     
begin     
    declare @idx int     
    declare @slice varchar(8000)     
    
    select @idx = 1     
        if len(@String)<1 or @String is null  return     
    
    while @idx!= 0     
    begin     
        set @idx = charindex(@Delimiter,@String)     
        if @idx!=0     
            set @slice = left(@String,@idx - 1)     
        else     
            set @slice = @String     
        
        if(len(@slice)>0)
            insert into @temptable(Items) values(@slice)     

        set @String = right(@String,len(@String) - @idx)     
        if len(@String) = 0 break     
    end 
return     
end  
Comments [0] | | # 
# Monday, October 19, 2009
Monday, October 19, 2009 4:16:34 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET )


In classic ASP, it was very simple to include external content inside of your pages using INCLUDE FILE

<!--#INCLUDE FILE="../../dbase_connection.asp"—>

I didn’t think this was possible in ASP.NET until I came across this little example from MSDN.

<%@ Page Language="vb" %>
   <html>
   <body>
        <%           
          Response.WriteFile ("Myfile.inc")
        %>
   </body>
   </html>
Comments [0] | | # 
# Thursday, October 15, 2009
Thursday, October 15, 2009 9:23:55 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Remember that a CheckBoxList is rendered as a table in the browser.   To find each item, we need to look in the <table> tag for each item. But the text for each item is rendered in a <label> tag.

Here is a working demo.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Highlight A Selected CheckBox Item</title>
    <script language="javascript" type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function() {
            $("table[id$=MyCheckboxList] input").click(function() {
                if ($(this).next().is(".selected")) {
                    $(this).next().removeClass("selected").addClass("notselected");
                }
                else {
                    $(this).next().removeClass("notselected").addClass("selected")
                }
            });          
        });
    </script>
    <style type="text/css">
        .selected
        {
            background-color:Green;
        }
        .notselected
        {
            background-color:White;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">   
        <asp:CheckBoxList ID="MyCheckboxList" runat="server">
            <asp:ListItem Text="vanilla"></asp:ListItem>
            <asp:ListItem Text="chocolate"></asp:ListItem>
            <asp:ListItem Text="strawberry"></asp:ListItem>
        </asp:CheckBoxList> 
    </form>
</body>
</html>

In the code above, use the following\jQuery selector to find the CheckBoxList items:

$("table[id$=MyBoxList] input")
Comments [0] | | # 
Thursday, October 15, 2009 8:40:21 PM (GMT Daylight Time, UTC+01:00) ( )


You can set the CommandName property to any valid string that identifies the command to perform when a button is clicked. You can then programmatically determine the command name from the CommandEventArgs of the parent data-bound control and perform the command appropriately.

There are a couple of ways of doing this.

Method 1:

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

    Dim clickedButton As Button = sender
    If clickedButton.CommandName = "Update"
        'Update something
    Else
        'Do something else
    End If 

End Sub

<asp:Button id="UpdateButton" CommandName="Update" Text="Update Field" OnClick="UpdateCreatedDate_Fields" runat="server" />
<asp:Button id="AddButton" CommandName="Add" Text="Add New Field" OnClick="UpdateCreatedDate_Fields" runat="server" />


Method 2:

<SCRIPT Runat="Server">

Sub Do_Processing (Src As Object, Args As CommandEventArgs)

  If Args.CommandName = "Process1" Then
    ...do this processing
  End If

  If Args.CommandName = "Process2" Then
    ...do this processing
  End If
    
End Sub

</SCRIPT>

<form Runat="Server">

<asp:Button OnCommand="Do_Processing" CommandName="Process1" Runat="Server"/>
<asp:Button OnCommand="Do_Processing" CommandName="Process2" Runat="Server"/>

</form>
 
Additional Resources:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.commandname.aspx

http://www.maconstateit.net/tutorials/aspnet20/ASPNET05/aspnet05-01.aspx
Comments [0] | | # 
# Wednesday, October 14, 2009
Wednesday, October 14, 2009 1:56:23 AM (GMT Daylight Time, UTC+01:00) ( )

test

Comments [0] | | # 
# Monday, October 12, 2009
Monday, October 12, 2009 10:07:30 PM (GMT Daylight Time, UTC+01:00) ( )


What could more .NET-like than drawing Homer

http://www.wikihow.com/Draw-Homer-Simpson

Comments [0] | | # 
# Thursday, October 08, 2009
Thursday, October 08, 2009 5:51:03 PM (GMT Daylight Time, UTC+01:00) ( )


This article shows you how to limit characters entered in an ASP.NET Multiline TextBox. The ASP.NET Multiline TextBox ignores the MaxLength property. So one of the ways of solving this requirement is to use Client Script and detect if the maximum character limit of the Multiline TextBox has been reached. If the number of characters exceeds the maximum, then the submit button is also disabled.

Here is a working demo.

<html> 
  <head> 
    <title></title> 
    
    <style type="text/css">
    .exceededCharacters{
        background-color:red;
    }
    </style>
    
    <script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js"></script> 
               
    <script type="text/javascript">
        $(function() {
            var limit = 50;
            var txt = $('textarea[id$=Textbox1]');
            $(txt).keyup(function() {
                var len = $(this).val().length;
                if (len > limit) {
                    $(this).addClass('exceededCharacters');
                    $('#status').text(len - limit + " characters exceeded");
                }
                else {
                    $(this).removeClass('exceededCharacters');
                    $('#status').text(limit - len + " characters left");
                }
            });
 
            $('input[id$=btnSubmit]').click(function(e) {
                var len = $(txt).val().length;
                if (len > limit) {
                    e.preventDefault();
                }
            });
        });
    </script>   
   
  </head> 
  <body> 
  <form runat="server">
    <div class="smallDiv">
        <h2>Type into this textbox which accepts 50 characters overall</h2>
        <asp:TextBox ID="Textbox1" runat="server" TextMode="MultiLine"/><br /> 
        (This textbox accepts only 50 characters) <br />
        <span id="status"></span> <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"/>
        <span id="error"></span>
        <br /><br />
        Tip: Clicking on the Submit button when number of characters are
        less than 50, results in a postback to same page. If you exceed 50
        characters, the exceeded characters are printed below the textbox
        and a postback is prevented.
    </div>
    </form>
    
  </body> 
</html>
Comments [0] | | #