Trusha Savsani
Trusha Savsani

Reputation: 479

Access code behind data into .aspx page


I have one record from sql database into code behind.
I want to use its fields into entire .aspx page.
What should i do?
My code is like:
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();
    }
}

I want to use different fields in different controls of .aspx page.
Controls like:
default.aspx

<asp:Label ID="diamond_carat_lbl" CssClass="diamond_carat_lbl" runat="server" Text=' ' ></asp:Label>

Upvotes: 0

Views: 125

Answers (1)

mason
mason

Reputation: 32693

So you might want to bind different values of your query result to some labels or textboxes? That should work. What's preventing you from doing that in code behind?

By the way, you should wrap your SqlConnection in a using statement since it implements IDisposable. That makes sure your connection gets disposed of properly, even if there's an error. And your code is vulnerable to SQL Injection attacks since you didn't parameterize your queries.

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");

Upvotes: 1

Related Questions