Hi narasiman,
Check this example. Now please take its reference and correct your code.
HTML
<asp:GridView ID="gvDetails" runat="server" />
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dtFarmerFarmReports = new DataTable();
dtFarmerFarmReports.Columns.AddRange(new DataColumn[3] {
new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Questions", typeof(string)) });
dtFarmerFarmReports.Rows.Add(1, "OLAM ", "{\"Produto prefer\":\"Algodão\",\"Plantou algodão\":\"Sim\"}");
dtFarmerFarmReports.Rows.Add(2, "OLAM ", "{\"Produto prefer\":\"Feijão Buer\",\"Plantou algodão\":\"Não\"}");
dtFarmerFarmReports.Rows.Add(3, "OLAM ", "{\"Produto prefer\":\"Buer\",\"Plantou algodão\":\"Jao\"}");
DataTable dtQuestionText = new DataTable();
dtQuestionText.Columns.AddRange(new DataColumn[4] {
new DataColumn("Id", typeof(int)), new DataColumn("Name"), new DataColumn("QuestionText"), new DataColumn("QuestionValue") });
foreach (DataRow row in dtFarmerFarmReports.Rows)
{
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(row["Questions"].ToString());
foreach (var items in dict)
{
dtQuestionText.Rows.Add(Convert.ToInt32(row["Id"]), row["Name"].ToString(), items.Key, items.Value);
}
}
DataTable dtDynamicColumn = new DataTable();
dtDynamicColumn.Columns.AddRange(new DataColumn[] { new DataColumn("Id", typeof(int)), new DataColumn("Name") });
var distinctColumn = dtQuestionText.AsEnumerable().Select(x => x.Field<string>("QuestionText")).Distinct().ToList();
for (int i = 0; i < distinctColumn.Count; i++)
{
dtDynamicColumn.Columns.Add(distinctColumn[i], typeof(string));
}
for (int i = 0; i < dtQuestionText.Rows.Count; i++)
{
dtDynamicColumn.Rows.Add();
dtDynamicColumn.Rows[i][0] = Convert.ToInt32(dtQuestionText.Rows[i]["Id"]);
dtDynamicColumn.Rows[i][1] = dtQuestionText.Rows[i]["Name"].ToString();
DataTable selected = dtQuestionText.Select("Id=" + Convert.ToInt32(dtQuestionText.Rows[i]["Id"])).CopyToDataTable();
for (int j = 0; j < selected.Rows.Count; j++)
{
if (selected.Rows[j][2].ToString().ToLower() == dtDynamicColumn.Columns[2].ToString().ToLower())
{
dtDynamicColumn.Rows[i][2] = selected.Rows[j][3].ToString();
}
else if (selected.Rows[j][2].ToString().ToLower() == dtDynamicColumn.Columns[3].ToString().ToLower())
{
dtDynamicColumn.Rows[i][3] = selected.Rows[j][3].ToString();
}
}
}
dtDynamicColumn = dtDynamicColumn.DefaultView.ToTable(true);
gvDetails.DataSource = dtDynamicColumn;
gvDetails.DataBind();
}
}
Screenshot