我必须根据以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();
}发布于 2013-04-16 00:02:06
我注意到了几件事:
最重要的是,当您将用户输入的值直接传递到数据库中时,您是高度vulnerable to sql-injection attacks的。你可以使用avoid this by using a parameterised query。
-Secondly,则需要过滤WHERE子句中的记录。此时,您正在将用户键入/选定的值分配到select查询中。
-And您需要使用下拉列表的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();发布于 2013-04-15 23:32:48
尝尝这个,
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();发布于 2013-04-15 23:34:45
添加以下代码:
您的SqlDataAdapter和SqlCommand没有通信。
而且您还没有用结果填充Datatable。
da.SelectCommand = cmd;
da.fill(dt);https://stackoverflow.com/questions/16019067
复制相似问题