Dim Dim - 6 months ago 10
SQL Question

For each sql column "mobile" sent it to a richTextBox

i'm using this code for senting column "mobile" (From Sql) to a richTextBox, but it sents only one mobile, i want sent them all.

SqlCommand command =new SqlCommand("select * from memberform ", con);
con.Open();
SqlDataReader read = command.ExecuteReader();
while (read.Read())
{
richTextBox1.Text = (read["mobile"].ToString());
}
read.Close();


Also how can i add a comma after every mobile?

Answer

You may be retrieving several records from the table, but in the while-loop you're constantly overwriting the results. You're setting the value of richTextBox1.Text in each loop over an over again which results in only the last record being written to the textbox.

This can be fixed relatively simple by adjusting the line in the loop to this (notice the +=):

richTextBox1.Text += read["mobile"] + ", ";

This approach may be a bit cleaner:

con.Open();
using (var command = new SqlCommand("select mobile from memberform ", con)) // only retrieve the column, you really need
using (var reader = command.ExecuteReader())
{
    var stringBuilder = new StringBuilder();
    while (reader.Read())
    {
        stringBuilder.Append(reader["mobile"] + ", ");
    }

    string result = stringBuilder.ToString().TrimEnd(',', ' ');
    richTextBox1.Text = result;
}
Comments