Paul Rajs

Paul Rajs

  • NA
  • 641
  • 138.6k

How to Get and Assign a column name dynamically from datatable using c

Jul 1 2021 11:33 AM

Hi Developers,

I have done the generate hyperlink column dynamically and working fine as get from Column names database.

However suppose some one change the naming convension on database sp it will not work or throw error. 

So now am need to bind the respective column names dynamically.am using the following C# code

if (responseCode == 0)
{
    var obj = JObject.Parse(JsonConvert.SerializeXmlNode(doc));
    GetClassWiseInventoryDetails = obj["Response"]["GetClassWiseInventoryDetails"].ToString();

    // Get Class Wise Inventory Details
    XmlNodeList DataClassWiseInventoryDetails = doc.GetElementsByTagName("GetClassWiseInventoryDetails");
    DataTable dtClassWiseInventoryDetails = Dynamic.ConvertXmlNodeListToDataTable(DataClassWiseInventoryDetails);
    if (dtClassWiseInventoryDetails.Columns.Contains("CLASS_ID"))
    {
        foreach (DataRow drClassWiseInventoryDetails in dtClassWiseInventoryDetails.Rows)
        {
            // Get Basic Details Hyper Link                                       
            foreach (DataColumn column in dtClassWiseInventoryDetails.Columns)
            {
                // Current ouput
                drClassWiseInventoryDetails["Vehicle_Type"] = "<a style='color:blue' href='#' onclick='return ViewBasicDetails(&quot;" + drClassWiseInventoryDetails["AgentId"] + "," + drClassWiseInventoryDetails["CLASS_ID"] + "," + 2 + "&quot;);' title='Click To View'>" + drClassWiseInventoryDetails["Vehicle_Type"] + "</a>";
                drClassWiseInventoryDetails["Total_Tags"] = "<a style='color:blue' href='#' onclick='return ViewBasicDetails(&quot;" + drClassWiseInventoryDetails["AgentId"] + "," + drClassWiseInventoryDetails["CLASS_ID"] + "," + 2 + "&quot;);' title='Click To View'>" + drClassWiseInventoryDetails["Total_Tags"] + "</a>";

                //Expected Output
                drClassWiseInventoryDetails[BindCoumnNameDynamically] = "<a style='color:blue' href='#' onclick='return ViewBasicDetails(&quot;" + drClassWiseInventoryDetails["AgentId"] + "," + drClassWiseInventoryDetails[BindCoumnNameDynamically] + "," + 2 + "&quot;);' title='Click To View'>" + drClassWiseInventoryDetails[BindCoumnNameDynamically] + "</a>";
                drClassWiseInventoryDetails[BindCoumnNameDynamically] = "<a style='color:blue' href='#' onclick='return ViewBasicDetails(&quot;" + drClassWiseInventoryDetails["AgentId"] + "," + drClassWiseInventoryDetails[BindCoumnNameDynamically] + "," + 2 + "&quot;);' title='Click To View'>" + drClassWiseInventoryDetails[BindCoumnNameDynamically] + "</a>";
            }
        }
    }
}

If anyone know how to complete this kindly help me to done this task.

Thanks and Regards,

Paul.S


Answers (2)