Click here to Skip to main content
15,882,209 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have one query table that holds three columns namely id, name, query. I want to bind id as a value name as a text in drop down and when I change the drop down list that query column is executed in web grid dynamically. I don't know how to do this.


Qry_ID	Qry_Name	Qry_Query
    ------------------------------------------------------------------------
1     customer    select cus_name, cus_street, cus_address, cus_place, cus_mobile from customer_master
2     supplier    select sup_code, sup_name from supplier_master


What I have tried:

i dont know how to do this. if any answer please reply me
Thank you
Posted
Updated 28-Aug-19 2:43am

1 solution

C#
private DataTable DynamicTableResult(string tableType)
{
   // based on the table type parameter pass your query 
    var sql = "select sup_code, sup_name from supplier_master";
	var result = new DataTable();
	using (var context = new YourDbContext())
	{
		var cmd = context.Database.Connection.CreateCommand();
		cmd.CommandType = CommandType.Text;
		cmd.CommandText = sql;

		try
		{
			context.Database.Connection.Open();
			var reader = cmd.ExecuteReader();
			do
			{
				result.Load(reader);
			} while (!reader.IsClosed);
		}
		finally
		{
			context.Database.Connection.Close();
		}
	}

	return result;
}


Your Controller

C#
// tableType will hold Customer/Supplier
public ActionResult Index(string tableType)
{
     DataTable dt = DynamicTableResult(tableType);
     return View(dt);
}


Your View will be like

HTML
@using System.Data
@model DataTable

<table cellpadding="0" cellspacing="0">
    <tr>
        @foreach (DataColumn col in Model.Columns)
        {
            <th>@col.ColumnName</th>
        }

    </tr>
    @foreach (DataRow row in Model.Rows)
    {
        <tr>
            @foreach (DataColumn col in Model.Columns)
            {
                <td>@row[col.ColumnName]</td>
            } 
        </tr>
    }
</table>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900