简体   繁体   中英

How to bind grid view data based on the dropdown list selected value

I have one drop down list to select student name.when i select a student name in the drop down list, grid view has to show details of selected name. This is my coding for this but it didn't display anything.

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MGLCOMConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT VALUE,VDESC FROM CSOPTFD WHERE OPTFIELD='WONO'AND VALUE LIKE '%" + customerddl.SelectedValue + "%'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();

this is my cs code to get the details of selected value.But it didn't any thing.

VALUE is a reserved keyword for T-SQL. Use it with square brackets like [VALUE]

And please use parameterized queries instead. This kind of string concatenations are open for SQL Injection attacks.

SqlCommand cmd = new SqlCommand("SELECT [VALUE], VDESC FROM CSOPTFD WHERE OPTFIELD = 'WONO' AND [VALUE] LIKE '%' + @value + '%'", con);
cmd.Parameters.AddWithValue("@value", customerddl.SelectedValue);

您是否正确绑定了Dropdown,如CustomerId,Text,之后您是否通过PostBack True从Selected_Index_Changed事件中调用此代码?

Try providing the code in a try - catch block. Use the finally block to closed the connection by using con.Close();

Also try closing the connection and then accessing the dataset for values.

SqlConnection con =null;
DataSet ds=null;
try
{
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["MGLCOMConnectionString"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT VALUE,VDESC FROM CSOPTFD WHERE OPTFIELD='WONO'AND VALUE LIKE '%" + customerddl.SelectedValue + "%'", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        ds = new DataSet();
        da.Fill(ds);

}
catch(SQLException ex)
{

}
finally
{
     if(con!=null)
         con.Close();
}
GridView1.DataSource = ds;
GridView1.DataBind();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM