Category Archives: FormView

[RESOLVED] Add a a first default item to a Drop Down List


I fill a the drop down list with a SQL select query, but i want to add a first default item, something like "- Select an option -" or "All" 

What im trying to do is make a dynamic SQL query, something like this:

SELECT * FROM table1 WHERE (value1 = ? AND value2 = ? AND value3 = ? )........ (or "like" instead of "=")

You are gonna have to select those arguments from 3 drop down lists, but i wanna have a default value on the top of the drop down list options and send a "*" as value if this option its selected, so the filter doesn't consider that value

Any Ideas?

This can be accomplished in code behind. Are you using or

Here's some code that you could use (adapt it for your own uses) 

DropDownList ddlDropDown = ((DropDownList)FormView1.FindControl("ddlDropDown"));
ddlDropDown.Items.Add(new ListItem("-- Select Option --","-1"));
ddlDropDown.AppendDataBoundItems = true;


Private Sub Fill_List()
        Dim list_dt As New DataTable
        list_dt = objList.Bind_List() '' Its return data table
        ddl_list.DataSource = list_dt.DefaultView
        ddl_list.DataTextField = "List_Name"
        ddl_list.DataValueField = "List_Id"
        ddl_list.Items.Insert(0, New ListItem("Select List", "-1")) '' This is first line in your dropdown box.

End Sub

In C#:

private void Fill_List()
	DataTable list_dt = new DataTable();
	list_dt = objList.Bind_List();
	//' Its return data table
	ddl_list.DataSource = list_dt.DefaultView;
	ddl_list.DataTextField = "List_Name";
	ddl_list.DataValueField = "List_Id";
	ddl_list.Items.Insert(0, new ListItem("Select List", "-1"));
	//' This is first line in your dropdown box.




This look perfect. Let me check if this work and i let you know.

Its good to see that your problem has been solved.


This is what i do

  1. DropDownList ddl = DropDownList1;  
  2. ddl.Items.Add(new ListItem("-- Select Option --","-1"));  
  3. ddl.AppendDataBoundItems = true;  

Is this correct? I couldnt get the DropDownList from the FindControl, i was getting just nulls

[RESOLVED] Formview with DropdownList


I'm sure this is really simply, but I'm having a hard time figuring out how to accomplish it. 

I have a Formview control on my page to view all my records from a SQL databases.  I want the users to be able to select the first textbox inside Formview called "Name" and it automatically pull up and show information about that record based on the selection inside Formview. Is this something I can do with SelectedIndexChange?  Thanks for the help! I'm using C# and VS 2010. 

Set AutoPostBack="true" for the TextBox and use OnTextChanged Event of the TextBox to pass the text entered to your database query.

[RESOLVED] best way to handle having user submit long text

I have a web application where users are permitted to submit their resumes. When the form is submitted, the data is inserted into a new record in an SQL table.

One of the fields in the form allows them to copy and paste their entire resume text into a TextBox control, which is inside the InsertItemTemplate of a FormView. This particular control is bound to a column in the SQL table that's of datatype nvarchar(MAX).

It works, but there are no line breaks and when viewed the resume is just one long continuous block of text.

How can I change this so that line breaks are preserved?

Do I need to use something like a "cute editor" control?

And finally, how do I protect against malicious code? The insert query is parameterized, and the FormView refers to an insert method in a TableAdapter in my dataset.


Line breaks in Textbox control is just line notepad - they represented by carriage returns, not the HTML <br> tags.

When displaying in html, just do a replace...  resumeText.Replace("\n","<br/>") 

Using the textbox is safer than "cute editor" as it prevents the ability for users to input html format which may contain malicious client side script and poorly formatted html. Just need to do proper replacing of single quotes which the equivalent "&039;". Single quotes in the query string are dangerous for sql injection. Also strip any html tags from the content.

Thanks for the explanation.

Just curious, though, how come the "\n" doesn't appear in the output?

Should I do the substitution in the code behind of the page that displays the resume?

And the other replacements you mention....where would that happen? In the INSERT query itself?

I tried this:

And got an error:

Server Error in '/' Application.

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1061: 'object' does not contain a definition for 'Replace' and no extension method 'Replace' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Source Error:

Line 16:             <p><asp:Label ID="date_postedLabel" runat="server" Text='<%# Convert.ToDateTime(Eval("date_posted")).ToShortDateString() %>' /></p>
Line 17: <p><asp:Label ID="categoryLabel" runat="server" Text='<%# Eval("category") %>' /></p> Line 18: <p><asp:Label ID="resumeLabel" runat="server" Text='<%# (Eval("resume")).Replace("\n","<br />") %>' /></p> Line 19: <p><asp:Label ID="fileLabel" runat="server" Text='<%# Eval("file") %>' /></p> Line 20: </ItemTemplate>

Source File: e:\Ed data\clients\Maine Innkeepers\MIA website 2010\Maine Innkeeper Site 2010\member\resume-detail.aspx    Line: 18


What am I doing wrong here?

OK, I have this working now, for some reason I had to add .ToString() to resolve the error:

<asp:Label ID="resumeLabel" runat="server" Text='<%# Eval("resume").ToString().Replace("\n","<br />") %>'/>

Thanks for the help.

Still curious about the second part of my question, though, regarding where to check the string before the insert happens. 

If you're worried about malicious code, then use a Stored Procedure to store data back to the database. Stored Procedures will take the values as they are w/o processing anything as extra code.

Or you could go through and remove any database keywords of the Resume like DELETE or UPDATE and removing ;'s on the coding side of things before the database gets updated. 



Alternative way, if the user resume included html format, you can also consider to use some editor control, like freetextbox or richtextbox. Use these control, you do not care about the format of user input.

Mister Ed

how do I protect against malicious code

Use parameterized value can prevent the sql injection attack to a great extent. You do not very worried about this.

And about script attacks. You can also use page validateRequest=true or server code Server.HtmlEncode to detete and encode user input before insert to database.

More information about Injection Attacks you can check these useful articles:

Hope this can help you.

[RESOLVED] Lock disable controls.

After user logs in, if user is of a particular role (I am using standard asp membership provider), I want to show the user a data entry form completely with locked/disabled controls (Readonly). User should be able to see the data, but not be able to edit any single control.

I have few individual web controls and data controls in the form. How can I do this. 


Hi use


if it equal to perticular role then set all controls ReadOnly property equals to true.



I want to show the user a data entry form completely with locked/disabled controls (Readonly). User should be able to see the data, but not be able to edit any single control.

If all the input controls are in a panel, you can just disable that depending on user role.

ps: You can also disable all input controls by looping page controls..

foreach (Control c in page.Controls)
		if (c is TextBox
		|| c is DropDownList
		|| c is RadioButton)

			(c as WebControl).Enabled = false;

Looks like a good solution, but I am not getting it to work..

This is the lay out structure I have.. I want to disable all controls from DivMain and downwards... DIV1, DIV2 ... etc.

<asp:Content id = "......>

     <asp:UpdatePanel id=".....>






















This is the lay out structure I have.. I want to disable all controls from DivMain and downwards... DIV1, DIV2 ... etc.

If all the controls are in UpdatePanel, have to disable like this..

foreach (Control c in UpdatePanel1.Controls)
                if (c is TextBox
                || c is DropDownList
                || c is RadioButton)
                    (c as WebControl).Enabled = false;
          // for controls in Updatepanel2
            foreach (Control c in UpdatePanel2.Controls)
                if (c is TextBox
                || c is DropDownList
                || c is RadioButton)
                    (c as WebControl).Enabled = false;
//Similarly for controls in other panels

Not working. 

After the update panel, there is the below structure... I put break point to see what is happening, the control c in the very first pass, is of UniqueId = IDctl00$MainContent$ctl01 .. it is not of any type of text box, dropdow, checbox, radio etc... for which I am checking... If I take the condition for checking type of control away and make it go to the c as webcontrol.enabled = false line of code, I get a Nullreferenceexception error..

Object reference not set to instance of an object message.... and c appears as null... something that I am doing wrong here.. thanks for your help...




          <FieldSet> ..







This work..?

foreach (Control c in UpdatePanel1.Controls)
                foreach (Control ctrl in c.Controls)
                    if (ctrl is TextBox)

                        ((TextBox)ctrl).Enabled = false;

                    else if (ctrl is RadioButton)

                        ((RadioButton)ctrl).Enabled = false;

                    else if (ctrl is CheckBox)

                        ((CheckBox)ctrl).Enabled = status;

                    else if (ctrl is DropDownList)

                        ((DropDownList)ctrl).Enabled = status;

Thank you for your help. That is the solution.

[RESOLVED] Compiler Error Message: BC30456: 'SelectedDate' is not a member of 'Calendar'.

hello all just trying to insert a record into database i have a couple of dropdown list and labels and textboxes and a calendar.  These things are all inside a formview and a objectdatasoure control.  When i run the page i get the following error : Compiler Error Message: BC30456: 'SelectedDate' is not a member of 'Calendar'.

Here is my code behind formview1.iteminserting:


    Protected Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles FormView1.ItemInserting
        If e.Values("flophours") = String.Empty Then
            e.Values("flophours") = 0
        End If
        If e.Values("mca1") = String.Empty Then
            e.Values("mca1") = 0
        End If
        If e.Values("mca2") = String.Empty Then
            e.Values("mca2") = 0
        End If
        If e.Values("mca3") = String.Empty Then
            e.Values("mca3") = 0
        End If
        If e.Values("vacation") = String.Empty Then
            e.Values("vacation") = 0
        End If
        If e.Values("notes") = String.Empty Then
            e.Values("notes") = "none"
        End If
        e.Values("dateinputed") = DateTime.Now
        e.Values("number") = 37891
        If e.Values("hoursworked") = String.Empty Then
            e.Values("hoursworked") = 0
            Dim Calendar1 As Calendar = TryCast(FormView1.FindControl("Calendar1"), Calendar)
            e.Values("dayworked") = Calendar1.SelectedDate.DayOfWeek
            e.Values("dayside") = True
            e.Values("nightside") = False
        End If

    End Sub

Any repley is welcome

Thanks Bob

Compiler might be considering Calendar as System.Globalization.Calendar and that's why you may be getting that error. Try specifying WebControls innstead

Dim Calendar1 As System.Web.UI.WebControls.Calendar = TryCast(FormView1.FindControl("Calendar1"), System.Web.UI.WebControls.Calendar)

you can debug this code

Dim Calendar1 As Calendar = TryCast(FormView1.FindControl("Calendar1"), Calendar)