CodersBarn.com
The ASP.NET Community Blog

DropDownList, DataBinding and RequiredValidator

October 17, 2009 10:40 by agrace

I recently had a DropDownList being pre-populated from a database. I also wanted to insert "Select" at the top of the list and make it a required field. Googling this yielded much misinformation for what turned out to be pretty simple to solve in the end.

Say you have a DDL like this:

<asp:DropDownList id="testDDL" runat="server">
    <asp:ListItem Text="Select"></asp:ListItem>
</asp:DropDownList>


If we try to populate this DropDownList from a database with the values 1,2 and 3, and then try and add a RequiredFieldValidator, that validator will not fire.

Some people resort to creating a CustomValidator and/or JavaScript here. This is not necessary. We need to take a step back here and re-phrase the problem: We already have data in our list in the shape of the "Select" item. We now want to append data from the database. A quick search of the MSDN documentation leads to the AppendDataBoundItems property for the DropDownList.

From the documentation: "The AppendDataBoundItems property allows you to add items to the ListControl object before data binding occurs. After data binding, the items collection contains both the items from the data source and the previously added items." The italics are mine...

We can use the InitialValue of the RequiredFieldValidator in conjunction with the AppendDataBoundItems property of the DropDownList to arrive at a working solution:

<asp:DropDownList id="testDDL" AppendDataBoundItems="true" runat="server">
    <asp:ListItem Text="Select"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="salaryReqVal" ControlToValidate="salaryDDL"
    ErrorMessage="*" Display="dynamic" InitialValue="Select"
        runat="server"></asp:RequiredFieldValidator>


kick it on DotNetKicks.com


Tags:
Categories: ASP.NET
Actions: E-mail | Permalink | Comments (4) | Comment RSSRSS comment feed

Input String was not in a Correct Format

August 16, 2009 09:42 by agrace
Incorrect Format

Here's the scenario: I'm building a basic 3-layer Web application for a client with business and data layers. Queries are performed in stored procedures, just basic ADO.NET. The table I am attempting to insert a record into has a range a field types such as strings, ints, decimals, etc.

If the user is entering integer or decimal values via texboxes, which is usually the case, then you have to expect either no data or a string of possibly mal-formed data. You must filter out the mal-formed data with validation and/or convert the resulting input data to the expected database type.

If you have a database field called SquareFeet of type int and you attempt to insert the following in your code-behind insert method, you will probably see this error:

// Results in error message
AddSomething(int squareFeet)
{
    Convert.ToInt32(SquareFeetTxtBox.Text.Trim());   
}


You must be careful if you are trying to fetch, say, an int or decimal as input:

// Correct way if SquareFeet field is an int
int squareFeet
if (int.TryParse(squareFeetTxt.Text.Trim(), out squareFeet))
    squareFeet = Convert.ToInt32(squareFeetTxt.Text.Trim());
else
     squareFeet = 0;
// Now insert the value as part of the record


// Correct way if SquareFeet field is a decimal
int squareFeet
if (decimal.TryParse(squareFeetTxt.Text.Trim(), out squareFeet))
    squareFeet = Convert.ToDecimal(squareFeetTxt.Text.Trim());
else
     squareFeet = 0.0m;
// Now insert the value as part of the record


References

Refer to these links for the differences between Convert.ToInt, int.Parse and Int.TryParse:
http://dotnetperls.com/int-parse-conversion
http://dotnetperls.com/int-tryparse

Refer to this link for an explanation of the 0.0m decimal syntax:
http://msdn.microsoft.com/en-us/library/364x0z75(VS.80).aspx

Moral of the Story
If you are learning any language, your first priority must be to understand the types thoroughly. Resist the temptation to gloss over the grammar just to get to the fancy stuff! :-)

kick it on DotNetKicks.com


Tags: , ,
Categories: ASP.NET | C#
Actions: E-mail | Permalink | Comments (8) | Comment RSSRSS comment feed

Fix for TreeView Jumping in Firefox

July 30, 2009 21:03 by agrace

I was working on a site tonight after being away from it for over three months. I came across some CSS and it took me a while to remember what it was for. I gleaned this online somewhere ages ago, but kudos and credit to the author whoever they are!

Jumping Treeview

For some time I have been having problems using the ASP.NET TreeView control in Sitemaps; every time I would hover over one of the parent nodes it would jump up and down. Here's some sample markup and the CSS to fix it in Firefox:

        <div id="idTreeView">
            <asp:TreeView ID="TreeView1" runat="server"                     DataSourceID="SiteMapDataSource1"
                    HoverNodeStyle-Height="0" Font-Bold="true" ImageSet="BulletedList">
                <RootNodeStyle Font-Bold="True" />
                <ParentNodeStyle VerticalPadding="0px" Font-Bold="True"                     Font-Underline="false"  />
                <HoverNodeStyle Font-Underline="false" ForeColor="#5555DD" />
                <NodeStyle Font-Bold="False" Font-Size="8pt" CssClass="sitelink"
                    ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px"                     VerticalPadding="0px" />
            </asp:TreeView>
           
            <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
        </div>


        div#idTreeView img
        {
            display: block;
            float: left;
        }

        div#idTreeView div
        {
            display: inline-block;
        }

        div#idTreeView .sitelink a
        {
            text-decoration:none;
        }


kick it on DotNetKicks.com   vote it on WebDevVote.com


Tags: ,
Categories: ASP.NET | CSS
Actions: E-mail | Permalink | Comments (6) | Comment RSSRSS comment feed

Set Color of GridLines in Gridview

May 31, 2009 07:04 by agrace

There are times when you will want to set the color of the grid lines in your GridView - however there is not to my knowledge a way of doing this declaratively. A workaround is to do this by tapping into the GridView's RowDataBound event.

GridView Gridlines

First, set the OnRowDataBound property in the markup of the GridView:

OnRowDataBound="MyGrid_RowDataBound"


Second, set the color in the OnRowDataBound handler method:

protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
     foreach (TableCell tc in e.Row.Cells)
     {
         tc.Attributes["style"] = "border-color: #c3cecc";
     }
}


Happy coding :-)

Update 06-01-2009:
See Lee's suggestion in the comments on a quicker way to do this:
Add this to the page Load method: this.GridView1.Attributes.Add("bordercolor", "c3cecc");

kick it on DotNetKicks.com   vote it on Web Development Community   411ASP.NET


CAT.NET New Build

March 21, 2009 12:57 by agrace

CAT.NET The Microsoft Connected Information Security Group (CIGS) has released an updated build of the CAT.NET tool.

There are some bug fixes and the ability to export results to Excel included in this release and users are advised to upgrade:

http://www.microsoft.com/downloads/details.aspx?FamilyId=0178e2ef-9da8-445e-9348-c93f24cc9f9d&displaylang=en


Note that this is the 32-bit version.