我有一条从sql数据库到后面的代码的记录
我想将其字段用于整个.aspx页面
我该怎么办?
我的代码如下:
default.aspx.cs
public partial class view_diamond : System.Web.UI.Page
{
public string id;
protected void Page_Load(object sender, EventArgs e)
{
//Label1.Text = Request.QueryString["diamond_id"];
if (!IsPostBack)
{
showData();
}
}
protected void showData()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["JemfindConnectionString"].ConnectionString);
conn.Open();
id = Request.QueryString["diamond_id"];
string sqlSelect = "SELECT * FROM diamond_detail WHERE final_diamond_id="+id;
SqlCommand cmd = new SqlCommand(sqlSelect, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
}
}
我想在.aspx页面的不同控件中使用不同的字段
控件如:
的Default.aspx
<asp:Label ID="diamond_carat_lbl" CssClass="diamond_carat_lbl" runat="server" Text=' ' ></asp:Label>
答案 0 :(得分:1)
因此,您可能希望将查询结果的不同值绑定到某些标签或文本框?这应该工作。什么阻止你在代码背后做到这一点?
顺便说一句,您应该将SqlConnection
包裹在using statement中,因为它实现了IDisposable。即使出现错误,也可确保您的连接得到妥善处理。由于您没有对查询进行参数化,因此您的代码很容易受到SQL Injection攻击。
id = Request.QueryString["diamond_id"]; //Probably should use String.IsNullOrEmpty and display a message to the client if the parameter isn't here
var cmd = new SqlCommand("SELECT * FROM diamond_detail WHERE final_diamond_id=@id");
cmd.Paramaters.AddWithValue("id", id);
var dt = new DataTable();
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["JemfindConnectionString"].ConnectionString));
{
cmd.Connection = conn;
conn.Open();
dt.Load(cmd.ExecuteReader()); //We eliminated the SqlDataAdapter
}
var record = dt.AsEnumerable().Single(); //retrieve one DataRow from DataTable
diamond_carat_lbl.Text = record.Field<string>("carats"); //Get the field called carats
diamond_name_lbl.Text = record.Field<string>("name");