I have been looking around the internet for a way to display specific content from a sql data table. I was hoping that I could display the Content column according to the Id column value.
views:
114answers:
2You probably want to have a look at some of these tutorials on asp.net and databinding
If you want to have exactly one value from one single record, you can use the ExecuteScalar
method of the SqlCommand
class:
string title = null;
using (SqlConnection conn = new SqlConnection("your-connection-string"))
using (SqlCommand cmd = new SqlCommand(
"select ContentTitle from {put table name here} where id = 4", conn))
{
conn.Open();
title = (string)conn.ExecuteScalar();
}
if (!string.IsNullOrEmpty(title))
{
// assign title to suitable asp.net control property
}
If you want to be able to do this for various ids, do not just concatenate a new sql string. I will repeat that: do not just concatenate a new sql string. Use parameters instead:
string title = null;
using (SqlConnection conn = new SqlConnection("your-connection-string"))
using (SqlCommand cmd = new SqlCommand(
"select ContentTitle from {put table name here} where id = @id", conn))
{
SqlParameter param = new SqlParameter();
param.ParameterName = "@id";
param.Value = yourIdGoesHere;
cmd.Parameters.Add(param);
conn.Open();
title = (string)conn.ExecuteScalar();
}
if (!string.IsNullOrEmpty(title))
{
// assign title to suitable asp.net control property
}
Update
Sample aspx page. First some markup (let's say the file is called example.aspx):
<body>
<form id="Form1" runat="server">
Title: <asp:Label id="_titleLabel"
Text="{no title assigned yet}"
runat="server"/>
</form>
</body>
...and in the code-behind (that would be called example.aspx.cs; I have included only the Page_Load event for simplicity):
protected void Page_Load(object sender, EventArgs e)
{
int id;
try
{
if (int.TryParse(Request.QueryString["id"], out id))
{
_titleLabel.Text = GetContentTitle(id);
}
else
{
_titleLabel.Text = "no id given; cannot look up title";
}
}
catch (Exception ex)
{
// do something with the exception info
}
}
private static string GetContentTitle(int id)
{
using (SqlConnection conn = new SqlConnection("your-connection-string"))
using (SqlCommand cmd = new SqlCommand(
"select ContentTitle from {put table name here} where id = @id", conn))
{
SqlParameter param = new SqlParameter();
param.ParameterName = "@id";
param.Value = yourIdGoesHere;
cmd.Parameters.Add(param);
conn.Open();
return (string)conn.ExecuteScalar();
}
}
Disclaimer: the code is written directly into the answer window and not tested (I don't have access to a development environment right now) so there may be errors