Blog

Blogging on programming and life in general.

Simple Way To Use A DataTable

Posted in: ASP.NET

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() });

blog comments powered by Disqus
;