Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I use SQL management studio and C#
So I need to get value from database and concatenate with new value and store in database
example
past value = "aaaaa"
New value = "bbbbb"
Need to store value = "aaaaa / bbbbb" like this

So I try like this but only get the last value like this
Ex
Last value sore in the database like this "ccc / bbb"
Application only get ccc but i want get all value "ccc / bbb"

this is my code get values


C#
string pastval , past;

using (SqlConnection conn = new SqlConnection(@"Data Source=MCK-PC\MCKSQL;Initial Catalog=application_database;Integrated Security=True"))
                {
                    conn.Open();
                    SqlCommand command = new SqlCommand("SELECT * FROM tbl1 WHERE id=@id", conn);
                    command.Parameters.AddWithValue("id", txt_id.Text);
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        pastval =reader["name"].ToString();
                        past= txtnew_name.Text +" / "+pastval.ToString();

                    }
                    reader.Close();
                    conn.Close();
                }

Thanks in advance !
Posted
Comments
Richard MacCutchan 3-Nov-13 11:16am    
You generate the string in variable past but you then overwrite it next time round the loop. Thus you only get the last entry at the end of the loop.
Manoj Chamikara 3-Nov-13 12:46pm    
@Richard
Thank Your quick response :)
OriginalGriff Solution (Solution 1) works

You need to append the text:
C#
StringBuilder sb = new StringBuilder(textnew_name.Text);
while (reader.Read())
{
    sb.AppendFormat(" / {0}", reader["name"])
}
past = sb.Tostring();
 
Share this answer
 
Comments
Manoj Chamikara 3-Nov-13 12:48pm    
@OriginalGriff
Griff Thank you so much dude It works
Thank you very very very Much
:)
OriginalGriff 3-Nov-13 14:31pm    
You're welcome!
Quote:

C#
SqlCommand command = new SqlCommand("SELECT * FROM tbl1 WHERE id=@id", conn);

You have got your answer, but I would like to mention one point here.

You have written SELECT *, which will select all Columns of the Table and is very time consuming.
But from the code, it is clear that you only need the Column "name" as you have written like reader["name"].

So, you should change the Query to...
C#
SqlCommand command = new SqlCommand("SELECT name FROM tbl1 WHERE id=@id", conn);
 
Share this answer
 
Comments
Manoj Chamikara 4-Nov-13 0:12am    
@Tadit
Correct
Thank you Dash !
Most welcome Manoj. :) My pleasure.

Thanks for the Up-vote and acceptance of answer.

Regards,
Tadit

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900