Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using StringBuilder with DataSet to build dynamic table

I'm using StringBuilder to dynamically contruct a table from a DataSet. It's in two parts, one to create the labels and their dimensions and column order. This part I have working already. What I'm stuck on is how to get the columns that have "values" then append the string to finish building the table.

There are 25 columns but typically the table with only have 17 or so. I also need to filter out the first column. I'm having trouble conceiving how to do this. This is what I have so far. All it does is pull out the first value in the DS. I can change the index number as well but in this case I can't really do that since the number and index of each column is unknown.

            DataSet valuesSet = getBlendInfo.GetProcessValues(reqID);

            foreach (DataRow dRow in valuesSet.Tables[0].Rows)
            {
                tblString.Append("<td>");
                tblString.Append(dRow[0].ToString());
                tblString.Append("</td>");
            }
like image 267
John Kinane Avatar asked Feb 04 '26 08:02

John Kinane


2 Answers

you just need to use a nested loop, something like this:

foreach (DataRow row in table.Rows)
{
    tblString.Append("<tr>");

    for (int i = 0; i < table.Columns.Count; i++)
    {
        tblString.Append("<td>");
        tblString.Append(row[i].ToString());
        tblString.Append("</td>");
    }

    tblString.Append("</tr>");
}

check for null before reading from row[i]

like image 178
Davide Piras Avatar answered Feb 05 '26 21:02

Davide Piras


Try:

DataSet valuesSet = getBlendInfo.GetProcessValues(reqID);
foreach (DataRow dRow in valuesSet.Tables[0].Rows)
{
    bool firstColumn = true;
    foreach (DataColumn dbColumn in valuesSet.Tables[0].Columns)
    {
        if (firstColumn)
            firstColumn = false;
        else
        {
            tblString.Append("<td>");
            tblString.Append(dRow[dbColumn].ToString());
            tblString.Append("</td>");
        }
    }
}
like image 41
Ɖiamond ǤeezeƦ Avatar answered Feb 05 '26 21:02

Ɖiamond ǤeezeƦ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!