Hi again,

I need an professional advise how to implement dropdownlist in very professional way. So, my code is:

<asp:DropDownList id="ddlStudents" runat="server" CssClass="textbox" OnSelectedIndexChanged="ddlStudents_SelectedIndexChanged" AutoPostBack="true" EnableViewState="true">
      <asp:ListItem Value="0">Choose</asp:ListItem>
    </asp:DropDownList>

The rest of data I get from SQL DB. Is it the right way to populate the default value by:

<asp:ListItem Value="0">Choose</asp:ListItem>

?

Thanks for future advice.

P.S Also, I have a label which shows a record from DB. DateTime. I need to format it someway that instead of "Birth: 15/10/2000 00:00:00" it will show only "Birth: 15/10/2000". I use SQL2005 for this project and there's no 'date' type.

Dani AI

Generated

Useful, practical follow-ups and fixes based on the thread (especially ’s loop bug and the suggestions from and ).

Do not add the placeholder inside the record loop — that creates a "Choose" entry for every row. Bind once (preferably only when Page.IsPostBack is false), dispose DB objects with using, and set DataTextField/DataValueField before calling DataBind. One robust server-side pattern is to fill a DataTable, add a computed full-name column, set the DataSource, and DataBind (example below).

protected void BindStudents()
{
  var dt = new DataTable();
  using(var conn = new SqlConnection(connection))
  using(var cmd = new SqlCommand("GetFullStudentProfile", conn))
  using(var da = new SqlDataAdapter(cmd))
  {
    cmd.CommandType = CommandType.StoredProcedure;
    da.Fill(dt);
  }
  dt.Columns.Add("FullName", typeof(string), "StudentName + ' ' + StudentFamilyname");
  ddlStudents.DataSource = dt;
  ddlStudents.DataTextField = "FullName";
  ddlStudents.DataValueField = "StudentID";
  ddlStudents.DataBind();
}

If you want a persistent "Choose..." item in markup, use AppendDataBoundItems so the declarative ListItem is preserved after DataBind:

<asp:DropDownList ID="ddlStudents" runat="server" AppendDataBoundItems="true">
  <asp:ListItem Value="-1">Choose...</asp:ListItem>
</asp:DropDownList>

Enforce selection with a RequiredFieldValidator (set InitialValue to the placeholder value). For display-only date formatting prefer formatting at the presentation layer — for example an ASP.NET data-binding expression lets you show only the date:

<asp:Label runat="server" Text='<%# Eval("BirthDate", "Birth: {0:dd/MM/yyyy}") %>' />

Short checklist: bind only when !IsPostBack, don’t insert the placeholder inside the data loop, use a sentinel placeholder value (e.g. -1 or empty) and server-side validation, and keep DB objects in using blocks. See the docs for AppendDataBoundItems, DataBinder.Eval and .NET date format strings for details:

Recommended Answers

All 4 Replies

when you are binding the dropdown from db then
after binding the dropdown you should right

ddlName.Items.Insert(0, new ListItem(Choose, "0"))

and dont insert listitem on HTML

I have a label which shows a record from DB. DateTime. I need to format it someway that instead of "Birth: 15/10/2000 00:00:00" it will show only "Birth: 15/10/2000".

You can do it in many ways,

In Code:
String.Format("{0:dd/MM/yyyy}", yourDateTime);

Or

In SQL:
SELECT CONVERT(varchar(10),yourDateTimeTyeColumnName,103)

when you are binding the dropdown from db then
after binding the dropdown you should right

ddlName.Items.Insert(0, new ListItem(Choose, "0"))

and dont insert listitem on HTML

Hi Malashukla, thanks for your advise, this method works. I say, it puts the 0 value for "Choose" text. You must have made a little mistake in your example by not inserting Choose word between the quotation marks. Please see how I've used it:

protected void GetStudents()
    {
        SqlConnection conn = new SqlConnection(connection);
        SqlCommand cmd = new SqlCommand("GetFullStudentProfile", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataReader reader;
        {
            try
            {
                conn.Open();
                reader = cmd.ExecuteReader();
                //ddlStudents.Items.Insert(0, new ListItem("Choose", "0"));
                while (reader.Read())
                {
                    
                    ListItem item = new ListItem();
                    item.Text = reader["StudentName"].ToString() + " " + reader["StudentFamilyname"].ToString();
                    item.Value = reader["StudentID"].ToString();
                    ddlStudents.Items.Insert(0, new ListItem("Choose", "0"));
                    ddlStudents.Items.Add(item);
                    
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                lbl.Text = ex.Message;
            }
            finally
            {
                conn.Close();
            }
        }
    }

I have much more studs in my DB.

You can do it in many ways,

In Code:
String.Format("{0:dd/MM/yyyy}", yourDateTime);

Or

In SQL:
SELECT CONVERT(varchar(10),yourDateTimeTyeColumnName,103)

Thank you Knvn very much.

I used the code-side approach and it worked perfect.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.