demouser
demouser

Reputation: 113

Adding multiple rows to a datatable for dynamically created columns

Hi all I am getting a string as follows for the data to be inserted as follows in a variable.

I have written a code to frame it as DataTable as follows:

 protected void Page_Load(object sender, EventArgs e)
        {
            var vData = "ID=1;Name='XYZ';ID=2;Name='PQR'";
            var values = vData.Replace(";", ",");
            var cols = values.Split(',');
            DataTable dt = new DataTable();
            for (int i = 0; i < cols.Length; i++)
            {
                var p = cols[i].Split('=');
                if (!dt.Columns.Contains(p[0].ToString()))
                    dt.Columns.Add(p[0].ToString());
            }
            DataRow dr = dt.NewRow();
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                var value = cols[j].Split('=');
                dr[j] = value[1];
            }
            dt.Rows.Add(dt);
        }

But this is adding only one row as the column will always be 2, but I need add multiple rows if the data exceeds

Upvotes: 1

Views: 10977

Answers (1)

mmssaann
mmssaann

Reputation: 1507

You can try the below, it is adding multiple rows.

What I did is, I counted ID using regex and add extra for loop below columns for loop.

var v = "ID=1;Name='XYZ';ID=2;Name='PQR';";
        string newRow = "ID";
        var values = v.Replace(";", ",");
        values = values.Remove(values.Length - 1, 1);
        var cols = values.Split(',');

        string pattern = Regex.Escape(cols[0].Split('=')[0]);
        var matches = Regex.Matches(v, "\\b" + pattern + "\\b", RegexOptions.IgnoreCase);
        int count = matches.Count;


        DataTable dt = new DataTable();

        for (int i = 0; i < cols.Length; i++)
        {
            var p = cols[i].Split('=');
            if (!dt.Columns.Contains(p[0].ToString()))
                dt.Columns.Add(p[0].ToString());
        }
        DataRow dr = null;
        int idxCol = 0;
        for (int k = 0; k < count; k++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                var value = cols[idxCol].Split('=');

                if (value[0] == newRow)
                {
                    dr = dt.NewRow();
                    dr[j] = value[1];
                }
                else
                {
                    dr[j] = value[1];
                }
                idxCol++;
            }
            dt.Rows.Add(dr);
        }

You can still re factor it and put the correct values. This is just way of idea to you.

Upvotes: 3

Related Questions