我需要从数据库中获取6个值并将它们绑定到链接按钮文本,她是代码
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string post = Request.QueryString["post"];
////string title = "nokia";
string date = DateTime.Now.ToShortDateString();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\nokiaoaq\Desktop\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
try
{
conn.Open();
//string str = "insert into Table1 (title , date_ ,www, cat) values (' " + TextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "')";
////string str = "INSERT INTO Table1 (title,date_,www ) values ('ddddddd','aaaaaaa','qqqqqq')";
string str =
//"SELECT from table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee";
"SELECT table1.title FROM table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee DESC";
SqlCommand objcmd = new SqlCommand(str, conn);
SqlDataAdapter da1 = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
da1.Fill(dt);
//DataRow dr = new DataRow();
//DataRow dr = ds.Tables[0].Rows[0];
foreach (DataRow dr in dt.Rows)
{
ml1.Text = dr[0].ToString();
ml2.Text = dr[1].ToString();
ml3.Text = dr[2].ToString();
ml4.Text = dr[3].ToString();
ml5.Text = dr[4].ToString();
ml6.Text = dr[5].ToString();
}
}
catch (Exception ex)
{
Label4.Text = "Failed to connect to data source";
}
finally
{
conn.Close();
}
}
}
ml是链接按钮ID
答案 0 :(得分:3)
您正尝试将返回的行中的6个字段分配给6个不同的文本框,但您的选择查询只会询问一个字段。如果要返回多个字段,请将其名称添加到选择查询中(将fieldX更改为相应的字段名称)。
string str = "SELECT title, field1, field2, field3, field4, field5 " +
"FROM table1 WHERE cat = 1 and datee=@dt ORDER BY datee DESC";
也不要使用字符串连接来构建sql语句。始终使用参数化查询
SqlCommand objcmd = new SqlCommand(str, conn);
objcmd.Parameters.AddWithValue("@dt", datee);
.....
这样可以避免格式化字符串,日期,数字等问题,还可以避免sql注入问题。
顺便说一下,我希望你的代码只返回一行,因为就现在而言,如果你有多行返回,那么只有具有最早日期的那一行才会显示在文本框中。 (如果是这种情况,则订单无用)。如果您返回了多行,则应考虑将数据表绑定到GridView以显示返回的所有记录。