数据列表控制;t绑定

本文关键字:绑定 控制 列表 数据 | 更新日期: 2023-09-27 18:09:30

我必须根据以find-frined形式插入的值绑定datalist control。这是我的代码:

protected void search_Click(object sender, EventArgs e)
    {
SqlConnection cn = new SqlConnection(@"Data Source=.'SQLEXPRESS;AttachDbFilename=C:'Users'Mahi'Documents'Visual Studio 2010'Projects'fc 6-4'fc'App_Data'fc.mdf;Integrated Security=True;User Instance=True");
        cn.Open();
        string str = "select unm='" + funm_txt.Text  + "' , university='" + DDLuni.SelectedItem + "', city='"+ DDLcity .SelectedItem +"' , yjoin='" + DDLyjoin.SelectedValue + "' ,yleave= '" + DDLycom.SelectedValue + "', ybatch='" + DDLbtch.SelectedValue + "' from profile";
        SqlCommand cmd = new SqlCommand(str, cn);
        cmd.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(str, cn);
        DataTable dt = new DataTable();
        DataList1 .DataSource =dt;
        DataList1.DataBind();
        cn.Close();
    }

数据列表控制;t绑定

我注意到了一些事情:

-首先,当您将用户输入的值直接传递到数据库中时,您是高度vulnerable to sql-injection attacks。您可以avoid this by using a parameterised query

-其次,您需要过滤WHERE子句中的记录。目前,您正在将用户键入/选择的值分配到选择查询中。

-您需要使用下拉列表的SelectedValue,而不是SelectedItem

-此外,您还可以使用using()块在末尾获得SqlConnection and DataAdapter Disposed

试试这个(请根据需要替换col1、col2,并完成分配所有参数的查询(:

DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection("your_conn_string"))
{
   string str = "Select Col1, Col2,... From profile " +
                "Where unm = @unm and university= @uni and " +
                "..." +
                "ybatch = @ybatch";
   SqlCommand cmd = new SqlCommand(str, cnn);
   cmd.Parameters.AddWithValue("@unm",funm_txt.Text);
   cmd.Parameters.AddWithValue("@uni",DDLuni.SelectedValue);
   ...
   cmd.Parameters.AddWithValue("@ybatch",DDLbtch.SelectedValue);

   using (SqlDataAdapter adapter = new SqlDataAdapter())
   {
     adapter.SelectCommand = cmd;
     cnn.Open();
     adapter.Fill(dt);
   }
}
DataList1.DataSource =dt;
DataList1.DataBind();

试试这个,

    cn.Open();
    string str = "select unm='" + funm_txt.Text  + "' , university='" + DDLuni.SelectedItem + "', city='"+ DDLcity .SelectedItem +"' , yjoin='" + DDLyjoin.SelectedValue + "' ,yleave= '" + DDLycom.SelectedValue + "', ybatch='" + DDLbtch.SelectedValue + "' from profile";
    SqlDataAdapter da = new SqlDataAdapter(str, cn);
    DataTable dt = new DataTable();
    da.fill(dt);
    DataList1 .DataSource =dt;
    DataList1.DataBind();
    cn.Close();

添加以下代码:

您的SqlDataAdapterSqlCommand没有通信。

并且您还没有用结果填充Datatable

da.SelectCommand = cmd;
da.fill(dt);