Add “Please select” message to databound dropdown list c#

So you have dropdown lists, populated with data from your data storage solution.  You need to prepend the lists with messages such as “Please select an option”.

 

 public void addMessageToDropdown(DropDownList whatDropdown, string ddmessage)
 {
    DropDownList list = whatDropdown as DropDownList;
    if(list != null)
    {
      list.Items.Insert(0, ddmessage);
    }
 
 }

 

Add years to dropdown

Need a dropdown list with some years in it and a custom message as the first choice? How about this to start with: current year through 6 years into the future. Add a dropdownlist control to the page and call this function on pageload.

public void addYearsToDropdown(DropDownList whatDropdown, string ddmessage)
 {
      DropDownList list = whatDropdown as DropDownList;
      if(list != null)
      {
          list.Items.Insert(0, ddmessage);
      }
      int curYear = System.DateTime.Now.Year - 1;
      for(int i = 1; i < 6; i++)
      {
          list.Items.Insert(i, (curYear + i).ToString());
       }
 }

addMessageToDropdown(DropDownListYears, “–Select A Year–“);

Checking boxes in a C# ASP checkbox list using values from a database

Suppose you have an ASP checkbox list and you need to check the boxes using data returned from the information storage.

You have a couple of ways the data could have been stored. If each checkbox option is a separate field in the database, you could go with a simple loop, but if they have been stored in one field, you need to put some programming power into it.

Here’s a scenario. I have a “seasons” checklist. There are values stored in the db that the user selected. For example if they chose Summer and Fall, the db string “seasons” would contain “Summer Fall”.

<asp:CheckBoxList ID="CheckBoxListSeasons" runat="server">
 <asp:ListItem>Summer</asp:ListItem>
 <asp:ListItem>Fall</asp:ListItem>
 <asp:ListItem>Winter</asp:ListItem>
 <asp:ListItem>Spring</asp:ListItem>
 </asp:CheckBoxList>

In order to display the list with the Summer and Fall boxes checked, I would do this:

string seasons = "Summer Fall"
for (int i = 0; i < CheckBoxListSeasons.Items.Count; i++)
 {

if (seasons.Contains(CheckBoxListSeasons.Items[i].Value))
 {

CheckBoxListSeasons.Items[i].Selected = true;
 }
 } // end checkbox loop

 

 

 

Prepend text “Select Value” to a databound dropdown list c#

You have a dropdown list, populated via sql data source, and you want it to have “Select a value” as the first selected option.

protected void DropDownList2_DataBound(object sender, EventArgs e)
        {
            DropDownList list = sender as DropDownList;
            if(list != null)
            {
                list.Items.Insert(0, "--Select Date--");
            }
        }

Loop through Visual Studio checkbox list c#

Its a bit easier using Javascript, but here is how to use c# and loop through the variables in a checkbox list control from Visual Studio.

You have a Checkbox List control on your page: CheckBoxList1. You  loop through the list of items and use the data…

In your codebehind, you are in a function to gather the data from objects:

myFunction(){...
// doing stuff
// need to get the data from the check box list checked items
string selectedItems = "";

for(int i = 0; i < CheckBoxList1.Items.Count; i++)
   {
      if (CheckBoxList1.Items[i].Selected)
                {
                  selectedItems += CheckBoxList1.Items[i].Value + ", ";
                 }
    }


...}

If the checkbox list had selected values of SUN, WED and FRI then the string selectedItems would contain the text : “SUN, WED, FRI, ”

I would use  a trim to remove the trailing comma.

 

Here is another method that casts the Checkbox items as a list and uses for each to loop through.

string FoundScholAppSport = "";
 foreach (ListItem val in CheckBoxListSports.Items)
 {
      if (val.Selected)
      {
          FoundScholAppSport += val.Value + " ";
      }
 }

Create Data Table C# datatable

Sometimes need to hand craft a data table for use.

DataTable dt = new DataTable();
        DataRow dr;
        dt.Columns.Add(new System.Data.DataColumn("EventTitle", typeof(String)));
        dt.Columns.Add(new System.Data.DataColumn("EventID", typeof(String)));
        dr = dt.NewRow();
        dr[0] = "Emergency Alert";
        dr[1] = "Event Id";

      dt.Rows.Add(dr);

Here is how you could use that in a function to return the datatable:

 private DataTable GetDummyData()
 {





DataTable dt = new DataTable();
 DataRow dr;
 dt.Columns.Add(new System.Data.DataColumn("EventTitle", typeof(String)));
 dt.Columns.Add(new System.Data.DataColumn("EventID", typeof(String)));
 dt.Columns.Add(new System.Data.DataColumn("Start_Time", typeof(String)));
 dt.Columns.Add(new System.Data.DataColumn("End_Time", typeof(String)));
 dt.Columns.Add(new System.Data.DataColumn("EventDetails", typeof(String)));


dr = dt.NewRow();
 dr[0] = "Christmas Party";
 dr[1] = "1";
 dr[2] = "12/23/2017 12:00:00";
 dr[3] = "12/23/2017 14:00:00";
 dr[4] = "Please drop by our Christmas party and bring gifts!";
 dt.Rows.Add(dr);

return dt;
 }

Custom command button in ASP gridview C#

A powerful feature to add your own button to the gridview and have custom commands. Most basic is you would want to pass the id of the record so you can do stuff to it.

In your gridview add a templatefield with a button as so…

<asp:TemplateField HeaderText="Actions">
     <ItemTemplate>
            <asp:Button runat="server" CssClass="btn btn-sm btn-danger" Text="Do Something" CommandName="CustomFunction" CommandArgument='<%# Eval("Id") %>'  /> 
     </ItemTemplate>
</asp:TemplateField>

 

Then you use the RowCommand event of the gridview to do what you need to…

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "CustomFunction")
            { string recordId = e.CommandArgument.ToString(); 
               // do what ever you need to do with the record id
             }
        }

Validate a textbox entry c# using tryParse

In strongly typed language, there is no room for error when a user enters data that is expected to be put into a data storage system.

For example, I need to covert an input from textbox1 that is supposed to be a number to be used in a total:

 int fundAmt = Convert.ToInt32(TextBoxPersonalFundAmt.Text);

 

If the user enters unexpected non numeric characters, this conversion will fail and make your app error out. Instead of directly trying to convert, we can cast a Boolean on our input data using TryParse to parse the number into an integer…

bool isNumeric = int.TryParse(TextBoxPersonalFundAmt.Text, out n);

Now we can validate the input and perform the necessary calculations with the numbers.

 

int fundAmt;
bool isNumeric = int.TryParse(TextBoxPersonalFundAmt.Text, out fundAmt);
       if (!isNumeric)
            {
              errInfo += "Error: Its not a valid number in the amount box ";
               lblLogErr.Text = errInfo;
                 pageValid = false;
                } else
                {
                    // calculate the total
                }

 

Another good example is the date field. A user is expected to enter  a valid date for their birthday. There are many ways that a user would normally express that date. We of course use a client side validation to ensure that the format is entered correctly, but we need to have a server side validation of that data as well.

 

DateTime SponsorSigDate;
            if(!DateTime.TryParse(TextBoxSponsorDate1.Text, out SponsorSigDate))
            {
               
                pageValid = false;
                errInfo += "Error: Enter a valid date. ";
            }