Dim Dim - 1 year ago 68
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);
SqlDataReader read = command.ExecuteReader();
while (read.Read())
richTextBox1.Text = (read["mobile"].ToString());

Also how can i add a comma after every mobile?

Answer Source

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:

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download