Simple Way To Use A DataTable

Published on
-
1 min read

When I normally create a datatable, I use quite a few lines of code just to add columns and input data into my DataTable.  But recently I have been using the following method use a DataTable in my code. The following function validates RadionButtonLists that I have in my page by passing the RadioButtonList size (rblSize) and RadioButtonList name (rblName).

//Function: Validate RadioButtonList for each question group
bool GroupValidateRBL(int rblSize, string rblName)
{
    bool validateOutput = true;
    int counter = 1;
   
    //Create DataTable object
    DataTable dt = new DataTable();

    //Add columns to DataTable
    dt.Columns.Add("No");
    dt.Columns.Add("RadioButtonName");
    dt.Columns.Add("Checked");

    while (counter <= rblSize)
    {
        ContentPlaceHolder cph = (ContentPlaceHolder)Page.Master.FindControl("ContentPlaceHolder1");
        RadioButtonList rbl = (RadioButtonList)cph.FindControl(rblName + counter);

       //Add Rows to Datatable
       dt.Rows.Add(new string[] { counter.ToString(), rblName, rbl.SelectedIndex.ToString() });
       counter++;
    }

    //Iterate through all rows in the DataTable to find all RadioButtonLists that have not been selected
    foreach (DataRow dr in dt.Rows)
    {
        if (Convert.ToInt32(dr["Checked"]) == -1)
        {
            validateOutput = false;
            break;
        }
    }
   return validateOutput;
} 

The DataTable in the function above stores a list of RadioButtonList entries and then iterates through each row in the DataTable to see if they have been selected. The data is entered into the DataTable by the following line:

dt.Rows.Add(new string[] { counter.ToString(), rblName, rbl.SelectedIndex.ToString() });

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.