0

i want to show a value in DropDownList at page load and the value is "1 Year". here is my Database Table

id  instal
0   Choose
6   6 Month
12  1 Year
24  2 Year
36  3 Year

here is my ASPX code:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
        DataSourceID="SqlDataSource1" DataTextField="instal" DataValueField="id" 
        onselectedindexchanged="DropDownList1_SelectedIndexChanged">
    </asp:DropDownList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:paconn %>" 
        SelectCommand="SELECT * FROM [cms_instal] ORDER BY [id]">
    </asp:SqlDataSource>
</asp:Content>

and its my C# code:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Collections;
using System.Web.SessionState;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList1.Text = "1 Year";
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}

but problem is that when my page is loaded it gives an error "'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value"

i am using ASP.Net C#, SQL Server 2008.

2

2 Answers 2

1

The text property of a DropDownList gets or sets the SelectedValue. Since your DataValueField is set to "id", you would need to set the Text property to "12".

Sign up to request clarification or add additional context in comments.

Comments

0

Move the text to the LoadComplete event

    void Page_LoadComplete(object sender, EventArgs e)
    {
        DropDownList1.Text = "1 Year"; 
    }

The list binding has not occurred in page load so the list is not able to take another value which is not in the list. Setting the value after page load will allow it to use an existing value.

1 Comment

You need to set the value after load event or after the control has binded properly as the list binding has not completed. So it needs to load up the values from the datasoure to allow it set a value from the list. msdn.microsoft.com/en-us/library/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.