GridView.RowDataBound Event No Data

I was trying to use the GridView.RowDataBound event to change the background color of the row in a GridView. But the data was missing. Here is what I trying:

void gvReport_RowDataBound(Object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
      if (e.Row.Cells[1].Text.IndexOf(“Total:”) > 0)
         e.Row.BackColor = System.Drawing.Color.FromArgb(247, 249, 223);
   }
}

But my e.Row.Cells[1].Text had no data in it. I am binding the grid in code so maybe that is why the grid would not show any data. Here is what I did to get it to work:

protected void gvReport_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
      DataRowView rowdata = (DataRowView)e.Row.DataItem;
      if (rowdata[1].ToString().IndexOf(“Total:”) > 0)
         e.Row.BackColor = System.Drawing.
Color.FromArgb(247, 249, 223);
   }
}

Hope this helps someone else.

 

Code to create a DataSet

Use this code to create a table and place it in a DataSet.

// Create a new DataTable.
System.Data.DataTable table = new DataTable(“Details”);
// Declare variables for DataColumn and DataRow objects.
DataColumn column;
DataRow row;
// Create new DataColumn, set DataType,
// ColumnName and add to DataTable.
column = new DataColumn();
column.DataType = System.
Type.GetType(“System.Int32”);
column.ColumnName =
“fk_agent_id”;
column.ReadOnly =
false;
column.Unique =
true;
// Add the Column to the DataColumnCollection.
table.Columns.Add(column);

// Create second column.
column = new DataColumn();
column.DataType = System.
Type.GetType(“System.String”);
column.ColumnName =
“agent_name”;
column.AutoIncrement =
false;
column.Caption =
“agent_name”;
column.ReadOnly =
false;
column.Unique =
false;
// Add the column to the table.
table.Columns.Add(column);

// Make the ID column the primary key column.
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = table.Columns[
“fk_agent_id”];
table.PrimaryKey = PrimaryKeyColumns;
// Instantiate the DataSet variable.
dataSet = new DataSet();
// Add the new DataTable to the DataSet.
dataSet.Tables.Add(table);

Code to create a DataRow and add it to a DataSet

Use this code to create a DataRow from a table in a DataSet and place it in the table in a DataSet.

// Call a method to create the DataSet with a table in it.

DataSet
resultData = MakeDetailTable();
DataRow row = resultData.Tables[“Details”].NewRow();
row[
“fk_agent_id”] = userInfo.account_id;
row[
“agent_name”] = userInfo.lname + “, “ + userInfo.fname;
resultData.Tables[“Details”].Rows.Add(row);

// Use the data in the GridView.
gvReport.DataSource = resultData.Tables[
“Details”];
gvReport.DataBind();

ASP.Net AJAX Animations

Some of the best resources for the animation framework that comes with the ASP.Net AJAX Control Toolkit can be found at the live toolkit site at this Sample Site. I often look at the Animation Reference section of this site.

While adding animations to ASP.Net pages, it is sometimes necessary to call animations directly from Javascript code. This can be achieved relatively easily using the great instructions at this MSDN blog.

Combined with the Animation Reference on http://asp.net/ajax website, any animation can be called directly from Javascript. If you can’t use the <OnLoad> animation event handler in the AnimationExtender control, one way to play animations on the page load is to use ClientScriptManager.RegisterStartupScript to create a function with the animation code, and call that function on the next line.


Page.ClientScript.RegisterStartupScript(Me.GetType, “PlayLoadAnimation”, “function playNotificationAnimation(){ AjaxControlToolkit.Animation.ColorAnimation.play($get(“”divNotification””) , 1 , 30 , “”style”” , “”backgroundColor”” , “”#181840″” , “”#E9E8FF””); }”, True)

Page.ClientScript.RegisterStartupScript(Me.GetType, “LoadAnimationFunction”, “playNotificationAnimation();”, True)

Happy Animating!
Zachary Lyons

Server.ScriptTimeout Not Working

I had a file upload page that gave an HttpException with message “Request timed out”. Natrually, I set the Server.ScriptTimeout to 360. But I still got the error rmessage. To solve this I added the following to the web.config file:

<httpRuntime
executionTimeout=360
maxRequestLength=41000 />

The maxRequestLength did not solve the problem by itself. The executionTimeout was needed as well.

 

Setting Page Meta Information at Runtime

I have a MasterPage and some child pages. The content for the child pages comes from a database. I have a form in the Admin section of my site for editing pages. You can set the Page Title, the Meta Description, Keywords, and page Content.

Accessing the title is easy, because the title of the content pages (in the @Page directive) applies to the MasterPage. Getting to the Meta information is a little trickier.

Thanks to Chris Garrett for his tip at http://aspalliance.com/411_Setting_the_ASPNET_Page_Title_and_Meta_Tags.

First, in the content pages, I have to add

<%@ MasterType VirtualPath=”~/MasterPage.master” %>

to the child pages, right under the @Page directive. With this, I can type “Master.” in the codebehind and access all the public properties of the MasterPage.

Second, on the MasterPage, I have to add two Public Properties. One for the Meta Description, and one for the Meta Keywords.

Public MetaDescription As String = “”
Public MetaKeywords As String = “”

Third, in the HTML code for the page, I make the two Meta tags server controls. I always set the Head tag to runat=”server”.

<head runat=”server” id=”Head1″>
<title
/>
<meta id=”Description” runat=”server” content=”description” name=”description”
/>
<meta id=”Keywords” runat=”server” content=”keys” name=”keywords” />

Fourth, on the Page_Load of the MasterPage, I can set the Title and Keywords at runtime.

Description.Attributes(“content”) = “Demo Description”
Keywords.Attributes(“content”) = “Keyword 1, Keyword 2”

I am now pulling the Meta information directly from the database at runtime, and setting Page.Title, Master.Description, and Master.Keywords from the Load event of the Child page.

In the Load event of the MasterPage, I can add some simple logic to give all pages a meta description.

If MetaDescription.Length = 0 Then
    Description.Attributes(“content”) = “My Generic Description. This description appears on all pages where the MetaDescription in the database is empty.”
Else
   
Description.Attributes(“content”) = MetaDescription
End If

If MetaKeywords.Length = 0 Then
   
Keywords.Attributes(“content”) = “Generic, Default, Consistent, Normal”
Else
   
Description.Attributes(“content”) = MetaKeywords
End If

This is how I use MasterPages, and it works pretty well!

Zachary Lyons

“Save As” Dialog Box for Streaming File

To download files using a “Save As” dialog box try this code:

        Select Case FileExt
            Case “gif” ContentType = “image/gif”
            Case “tif” ContentType = “image/tiff”
            Case “jpg” ContentType = “image/jpeg”
            Case “pdf” ContentType = “application/pdf”
            Case “avi” ContentType = “video/x-msvideo”
            Case “mp3” ContentType = “audio/mpeg”
            Case “mpg” ContentType = “video/mpeg”
            Case “wav” ContentType = “audio/wav”
            Case “rar” ContentType = “application/x-rar-compressed”
            Case “zip” ContentType = “application/x-zip-compressed”
            Case “exe” ContentType = “application/x-msdownload”
            Case Else
             ‘ FilePath = “”
             ContentType = “application/x-msdownload”
        End Select

        Response.Clear
        Response.Buffer = False
        Dim adoStream
        Set adoStream = Server.CreateObject(“ADODB.Stream”)
        adoStream.Open()
        adoStream.Type = 1
        adoStream.LoadFromFile(FilePath + “/” + FileName)
        Response.AddHeader “Content-Disposition”, “attachment;filename=” & Right(FileName,Len(FileName)-InStr(FileName,”/”))
        Response.ContentType = ContentType
        Response.BinaryWrite(adoStream.Read())
        adoStream.Close
        Set adoStream = Nothing
        Response.End

The ASP buffering limit is about 4 megs. Files larger than that will give an error like this:

   “Response Buffer to exceed its configured limit”

To stream out files larger than 4 Meg you can increase the “AspBufferingLimit” value. Edit the MetaBase.xml file in the C:\WINDOWS\system32\inetsrv folder. The default value is 4194304. Check the “Enable Direct Metabase Edits” check box before editing this file and you will not need to stop and start the WWW service.

SelectedValue which is invalid because it does not exist in the list of items

To populate drop down lists I bind the list to a lookup table in the database (i.e. States). Occasional the parent table (i.e. Customers) has a value that is “not on the list” and this error is genreated:

    ‘ddlState’ has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value

The only thing I’ve been able to figure out to do is add the parent table value to the drop down list. This only works when the value saved in the parent table is the actual value and not the foreign key (the ID of the child table such as StateID). Here is my code:

<asp:DropDownList ID=”ddlState” runat=”server” DataSourceID=”SqlDataSource1″ DataTextField=”StateName” DataValueField=”StateAbbr”></asp:DropDownList> <asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:DATABASE_01 %> SelectCommand=”SELECT [StateAbbr], [StateName] FROM [States] ORDER BY [StateName]”></asp:SqlDataSource>

Then in code:

Sub Page_Load()

ddlState.AppendDataBoundItems = True
Dim Items As New ListItem
Items.Text =
“Select One”
Items.Value = “”
ddlState.Items.Add(Items)

If Not IsPostback Then

… ‘ read data from database

… ‘  load values into controls

Items = New ListItem
Items.Text =
“” & rdUser(“State”).ToString
Items.Value =
“” & rdUser(“State”).ToString
ddlState.Items.Add(Items)
ddlState.SelectedValue =
“” & rdUser(“State”).ToString

 

I’ve tried putting a ‘Try/Catch’ around setting the ddlState.SelectedValue but that is not where the error occurs. The error occurs as the page is being rendered. When using the SqlDataSource control is used the data gets bound as the page is being rendered. The page load event occurs before the page is rendered so the drop down selected value is set before the data is bound! This method prevents the “does not exist” error messages all the time. If you have a better solution I’d sure like to hear it!