Monday, March 19, 2012

Database Select to Label

Hello!

I am tryingto select info from a database (MS-SQL) and show that whit a label. And don’t reallyget every thing to work. So I am glad for that help I can get.

SqlConnection myConnection =newSqlConnection();

myConnection.ConnectionString ="datasource='XXX';User ID='XXX';Password=XXX;database='XXX'";

myConnection.Open();

SqlCommand dataCommand =newSqlCommand();

dataCommand.Connection= myConnection;

dataCommand.CommandText ="SELECT XXX,XXX FROM XXX";

SqlDataReader dataReader =dataCommand.ExecuteReader();

string notis1 = dataReader;

Label1.Text = notis1;

myConnection.Close();

Any help whould be helpfoul.

You need to get the value you want from the DataReader.

string notis1;

while (dataReader.Read())
{
notis1 = dataReader.GetString("Some index");
}

...

dataReader.Close();

|||

Thanks for the help but still not get it to work perfectly. My code now is:

protected void Button1_Click(object sender, EventArgs e)
{
int notis_nr;
string notis_text, notis_rubrik;

SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = "data source='xxx';User ID='xxx';Password=xxx;database='xxx'";
myConnection.Open();
SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = myConnection;
dataCommand.CommandText = "SELECT NotisNr, NotisRubrik, NotisText FROM Notis";
SqlDataReader dataReader = dataCommand.ExecuteReader();

while (dataReader.Read())
{
notis_nr = dataReader.GetInt32(0);
notis_rubrik = dataReader.GetString(1);
notis_text = dataReader.GetString(2);
Label1.Text = notis_rubrik;
}

dataReader.Close();
myConnection.Close();

|||Have you tried running the query to see if it returns any results?|||

Brogren:

Thanks for the help but still not get it to work perfectly. My code now is:

protected void Button1_Click(object sender, EventArgs e)
{
...
while (dataReader.Read())
{
notis_nr = dataReader.GetInt32(0);
notis_rubrik = dataReader.GetString(1);
notis_text = dataReader.GetString(2);
Label1.Text = notis_rubrik;
}
...

What's the result you want? Your code will set Label1.Text to 2nd field value of the last row, as in the while loop the Label1.Text is being changed at each read of the SqlDataReader. If you want to concatenate strings from 2nd field of each row, you may need something like:

while (dataReader.Read())
{
notis_nr = dataReader.GetInt32(0);
notis_rubrik = dataReader.GetString(1);
notis_text = dataReader.GetString(2);
Label1.Text += notis_rubrik+"#";
}

|||

ThanksStrongTypes every thingworksperfectly!

But now Ihave decided to us a multiline textbox and I need that the text is exactly likeI want. The problem now is when I us a string a can’t use enter. So a text thatshoul look like this:

----

Hello

ASP.Net friends!

----

Looks likethis

----

Hello ASP.Netfriends!

----

I guess Iwill need to store my textbox like a html page or xml file But I really not getit right.

So I am helpfulfor any ides.

Big Smile

No comments:

Post a Comment