Add JQuery, Javascript, CSS to ASPx User Controls parent

Category : ASP.Net, C#, JQuery/JScript

This is my preferred method. (Microsoft has controls such as ScriptManager and ScriptManagerProxy but like nearly everything they do, I believe its overkill) To me, this is the simplest method.

The Problem: You want to convert or to create a user control that has scripts and/or css.

Solution: Within the Page_Load event of the user control, simply include the following:

    //For Scripts - notice we add this script call to the PARENT HEADER
    LiteralControl jQuery = new LiteralControl();
    jQuery.Text = "<script type=\"text/javascript\" src=\"js/jquery.js\"></script>";
    Page.Header.Controls.Add(jQuery);
 
    //For CSS - You could add Media under attributes as well.  
    HtmlLink stylesLink = new HtmlLink();
    stylesLink.Attributes["rel"] = "stylesheet";
    stylesLink.Attributes["type"] = "text/css";
    stylesLink.Href = "css/yourPagesCSS.css";
    Page.Header.Controls.Add(stylesLink);

Hope this helps someone! t

Getting a .net System.Drawing color from a Hex value.

Category : ASP.Net

So I’m using a jquery color picker, got to the back code where I was going to grab my colors and thought for a minute that there was no way to convert my HEX to one of the .Net system colors… (what am I thinking, WE should always remember that there is more than likely some class available to do what you need, as was the case here!)

SO YOU got a hex and need it to convert to a system color? Here ya go:

System.Drawing.ColorTranslator.FromHtml(“#FFFFFF”);

Thank you .Net
T

Send JSON via AJAX to JQuery from an aspx page.

Category : ASP.Net, JQuery/JScript

This took me many tries to get this right so I am logging this so I dont have to go through this again.

JSON (Javascript Object Notation) allows us to send data to our Javascript (JQuery) and let it read that data in very useful ways.  With JSON, we can send basic keys and values to Javascript (as I will show here) up to complete objects with parameters and functions ( just google JSON tutorials to see some amazing ways to use the data).

HERE I will show the following scenario:  using an aspx page (but it could just as easily be a simple html page) I declare the JQuery library and  using JQuery on that page  I make a call to another aspx page (so we can get to the server and do ‘thinking’ stuff) using one of JQuerys Ajax functions  (“$.post”) -  In that CALLED page I will be grabbing any sent in data (because our JQuery can send data to that page) , doing WHATEVER you want to do with the data (tap into a database, apply business rules, etc.) and then formatting whatever data you want to return in JSON format so that our JQuery can use it in a somewhat intelligent fashion.

I probably lost many of you, so let me just SHOW you and it will be much clearer.

STEP 1:  Markup – add the JQuery Library to your page, then call the $.post function (that function can take several types of configurations but the one I am using is the NAME of the page I am calling, the data I am sending to it, what to do with the Results I get back, and finally telling it that the results WILL BE IN JSON format.

<head runat="server">
    <title>JSON Test Page</title>    
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
 
    $(document).ready(function() {
        $("#jsonButt").click( function() {
                  $('#jsonReturnDiv').html( '<img src="images/loading.gif" />' );  
 
                  $.post('ajax/jsonTestPage.aspx',         
                        {'ThisIsWhereIWouldSendDataIn' : 'Data1', 'Data2Etc' : 'Data2'},  
                      //The data we return will come back as JSON
                       function(data) {                            
                           $('#firstReturnDiv').html(data.first);
                           $('#secondReturnDiv').html(data.second);
                           $('#thirdReturnDiv').html(data.third);
                           $('#jsonReturnDiv').html( '' );  
                        }, "json");
              });
 
     });  
     </script> 
</head>
<body>
    <form id="form1" runat="server">
        <div id="firstReturnDiv"> This is the first return div... check it</div>
        <hr />
        <div id="secondReturnDiv"> This is the second return div... check it</div>
        <hr /> 
        <div id="thirdReturnDiv"> This is the third return div... check it</div>       
        <hr />
        <input id="jsonButt" type="button" value="button" /> <div id="jsonReturnDiv"></div>
    </form>
</body>
</html>

If you dont understand the Document ready, butt click, and the rest then you should probably just read a couple QUICK JQuery tutorials — its very simple to pick up and very worthwhile. Basically the .click function is what Kicks the whole thing off so that when a user clicks a button on my page that I have set the ID to ‘jsonButt’. (I also kick off a lovely little whirly gig [ i love whirly gigs ] that I eventually hide after the data comes back) ….

STEP 2: Code Behind – So inside of my aspx page (the one I point to in the $.post function ( ‘ajax/jsonTestPage.aspx’, ) I remove ALL markup and only leave my top line “<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="jsonTestPage.aspx.cs" Inherits="ajax.jsonTestPage" %>” . Then in code behind I can grab the data that was sent in to the page via the Query string (I dont do this here) … the format the JSON data to return BACK to the page. *** TWO THINGS MUST BE PRESENT TO MAKE THIS WORK : THE CONTENT TYPE MUST BE SET AS I HAVE HERE AND THE JSON DATA HAS TO BE SURROUNDED BY DOUBLE QUOTES

        protected void Page_Load(object sender, EventArgs e)
        {
           // Response.ClearHeaders();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            //JSON MUST BE SENT BACK WITH THIS CONTENT TYPE!
            Response.ContentType = "application/json"; 
            //JSON MUST HAVE DOUBLE QOUTES!!!
            string jsonReturn = "{\"first\":\"This is the first\", \"second\":\"This is SECOND!\", \"third\" : \"This is third!\"}";
            Response.Write(jsonReturn);
        }

Now look at the jsonReturn string. We have a piece of data called ‘first’ and it’s value ‘This is the first’, etc… here is where we could make more complicated objects but we will keep it simple for now.

STEP 3 – This isnt really a step but just some explanation… The Response.Write now sends the data back to the page in JSON format. If you look again at our $.post function you will see that the return data (which we have appropriately named ‘data’) will be used here:

function(data) {
$(‘#firstReturnDiv’).html(data.first);
$(‘#secondReturnDiv’).html(data.second);
$(‘#thirdReturnDiv’).html(data.third);
$(‘#jsonReturnDiv’).html( ” );
},
Take note of how we were able to use the data simply now by calling data.first, data.second, etc… again, this is a simple (although elegant) use. This allows us to do many advanced things with our return data. We could even return an array of multiple objects and be able to use and manipulate and display them straight from Javascript.

Using this technique, one could write an elegant front end using ONLY JQuery and HTML while still being able to harness the power of IIS on the back end. Hope this helps someone! T.

Creating a TABLE in the code behind.

Category : ASP.Net, C#

This worked well for me.  I created the TABLE in markup [MAKE SURE ITS AN ASP:TABLE with the runat server tag].

Then you can manipulate it from code-behind like so:

   TableRow tr = new TableRow();
   TableCell tc = new TableCell();
   Label label2 = new Label();
   label2.Text = "LAJLKFJDSLJFLKDF";
   tc.Controls.Add(label2);
   tr.Cells.Add(tc);
   MyTable.Rows.Add(tr);

Hope this helps!

ASP.Net Page Lifecycle (page events)

Category : ASP.Net

I am not even going to try — here is the best and most complete description of the Page Lifecycle.

http://69.10.233.10/KB/aspnet/ASPNET_Page_Lifecycle.aspx (very nice and thanks UsualDosage)

Although I will list the Acronym that may help those of you who just need a quick reminder…. try this

  • S – Start
  • I  – Initialize
  • L  – Load
  • V – Validate
  • E – Event Handling
  • R – Render

caio

Filling a dropdown programatically in vb.net

Category : VB.Net

This is very simple but something I can never remember how to do!

 
'So we have a TABLE of data and want to put a title and value into a dropdown on our page.
For row As Integer = 0 To DT.Rows.Count - 1
            If Not DT.Rows(row).Item("Title") Is DBNull.Value And Not DT.Rows(row).Item("ID") Is DBNull.Value Then
 
                Dim a As New ListItem
                a.Value = districtDT.Rows(row).Item("Title")
                a.Text = districtDT.Rows(row2).Item("ID")
 
                myDropDown.Items.Add(a)
 
            End If
        Next

There you go!
t

Uploading a CSV to a Gridview in ASP.net

Category : ASP.Net, VB.Net

You have a CSV file and you would like to display it in a Gridview.

The finished product.

THE CODE:

1: Drop a FileUpload control on your canvas as well as a button for submitting the file and a gridview control.

2: Then add the System.IO, the variables, and the click event to the button.

Imports System.IO
 
Partial Public Class _Default
    Inherits System.Web.UI.Page
 
    Dim streamRdr As StreamReader
    Dim fileLines As String()
    Dim line As String
 
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
 
        If FileUpload1.HasFile Then
 
            Dim fileExt As String
 
            fileExt = System.IO.Path.GetExtension(FileUpload1.FileName)
 
            If fileExt = ".csv" Or fileExt = ".CSV" Then
 
                'Make variables needed
                Dim objStream As Stream
                Dim fileLen As Integer
 
                'Get the length of the file.
                fileLen = FileUpload1.PostedFile.ContentLength
 
                ' Create a byte array to hold the contents of the file.
                Dim Input(fileLen) As Byte
 
                'Move byte array into a stream, then start it at beginning and pass it to method.
                objStream = FileUpload1.PostedFile.InputStream
                objStream.Read(Input, 0, fileLen)
                objStream.Position = 0
 
                'Manage File
                importToDG(objStream)
 
            End If
 
        End If
 
    End Sub

3: Create the import Sub – you will need to create a Datatable, a row, and the columns that match your CSV. You need to put your CSV info into a datatable for the Gridview can bind to it.

Private Sub importToDG(ByVal fileStream As Stream)
 
streamRdr = New StreamReader(fileStream)
 
Dim myDTable As DataTable = New DataTable
Dim myDRow As DataRow = myDTable.NewRow
Dim schoolID, distID, schoolName, Address, Address2, Phone, City, State, Zip _
As New DataColumn
schoolID.ColumnName = "SchoolID"
distID.ColumnName = "DistrictID"
Phone.ColumnName = "Phone"
schoolName.ColumnName = "schoolName"
Address.ColumnName = "Address"
Address2.ColumnName = "Address2"
City.ColumnName = "City"
State.ColumnName = "State"
Zip.ColumnName = "Zip"
myDTable.Columns.Add(schoolID)
myDTable.Columns.Add(distID)
myDTable.Columns.Add(schoolName)
myDTable.Columns.Add(Address)
myDTable.Columns.Add(Address2)
myDTable.Columns.Add(Phone)
myDTable.Columns.Add(City)
myDTable.Columns.Add(State)
myDTable.Columns.Add(Zip)
 
'Now set the streamreader back to beginning.
streamRdr.DiscardBufferedData()
streamRdr.BaseStream.Seek(0, SeekOrigin.Begin)
streamRdr.BaseStream.Position = 0
 
Dim i As Integer = 0 'Skip the first row.
 
While Not streamRdr.EndOfStream
 
line = streamRdr.ReadLine 'Read first line
fileLines = line.Split(",") 'Split the line up by the delimeter
 
If i &gt; 0 Then
myDRow.ItemArray = fileLines
myDTable.Rows.Add(myDRow)
 
myDRow = myDTable.NewRow
End If
 
i += 1
 
End While
 
GridView1.DataSource = myDTable
GridView1.DataBind()
 
End Sub
 
End Class

And that is it!

COOKIES saving and reading in .Net

Category : ASP.Net, VB.Net

Here is the basic way to save and then read a cookie:

SAVING A COOKIE:

Private Sub buttSave_Click(ByVal sender as System.Object, _
ByVal e aAs System.EventArgs) Handles buttSave.Click
 
'Create the cookie
Dim usrCookie as New HttpCookie("UserInfo")
'Fill in the data
usrCookie("FirstName") = txtFirstname.Text
usrCookie("LastName") = txtLastname.Text
usrCookie("City") = txtCity.Text
usrCookie("ZIP") = txtZIP.Text
'Set expiration
usrCookie.Expires = DateTime.Now.AddDays(30)
'Add the cookie
Response.Cookies.Add(usrCookie)
End Sub

READING A COOKIE:

'Get cookie
Dim usrCookie Ad HttpCookie = Request.Cookies("UserInfo")
'Get data
txtFirstName.text = usrCookie("FirstName")
txtLastName.text = usrCookie("LastName")

SOMETHING TO REMEMBER:
Cookies ARE case sensitive! userInfoCookie and UserInfoCookie are not the same for cookies.

App_Code classes not showing up – Gotcha!

2

Category : ASP.Net

So you add a class to the App_Code folder but for some reason, you can’t see the class… frustrating right?

Well waste no more time.

For whatever reason (and I would love an explanation if someone knows) the App_Code folder sets elements’ build action to CONTENT. Simply change this to COMPILE and your classes will be visible.