我必须根据以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();
}
答案 0 :(得分:1)
我注意到的事情很少:
- 首先,当您将用户输入的值直接传递到数据库中时,您非常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();
答案 1 :(得分:0)
试试这个,
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();
答案 2 :(得分:0)
添加以下代码:
您的SqlDataAdapter
和SqlCommand
未通讯。
并且您尚未填写Datatable
结果。
da.SelectCommand = cmd;
da.fill(dt);