I know there are many questions related to create a dynamic query but no one can help me.
I am trying to create a dynamic cmd.Parameters.AddWithValue
with the help of foreach
loop but I can't find all the values that I pass in foeach
. I know I am writing var values = " " that's way the values give me null
value
I am providing my code may that help you to solve an error
public void insert_Para(System.Web.UI.HtmlControls.HtmlGenericControl ControlName, String TableName)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString()))
{
var values = "";
SqlCommand cmd = new SqlCommand("insert into "+ TableName +" values(" + values + ")", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
foreach (var item in ControlName.Controls)
{
if (item is TextBox)
{
cmd.Parameters.AddWithValue("@" + ((TextBox)item).ID, ((TextBox)item).Text);
values += "@" + ((TextBox)item).ID + ",";
}
}
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
}
}