Building Strings with Database Data

One of the items that I find myself doing quite often is passing data to the user in a string. For example, let’s say that you have a table with customer data and you want to show the user data with the customer’s name and phone number. Assume it should read: This customer’s last name is Smith and the phone number is 800-555-1212.

You could build that with something like:

        private void button1_Click(object sender, EventArgs e)
        {
            ConnectionStringSettingsCollection csc = ConfigurationManager.ConnectionStrings;
            if (csc != null)
            {
                foreach (ConnectionStringSettings connstr in csc)
                {
                    MessageBox.Show(connstr.ConnectionString, connstr.Name, MessageBoxButtons.OK);
                    var result = MessageBox.Show("Do you want to open?", "Question", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        OleDbDataAdapter dadapter = new OleDbDataAdapter("Select * from Customers", connstr.ConnectionString);
                        DataTable dt = new DataTable();
                        dadapter.Fill(dt);
                        DataRow dr = dt.Rows[2];
                        string str = "This customer's last name is " + dr[2].ToString() + " and the phone number is " + dr[6].ToString();
                        MessageBox.Show(str, "Info", MessageBoxButtons.OK);
                    }
                }
            }
        }

This will do the same loop as earlier, and you can see how the string is being built with the + operator. I have it looking at the third row (row 2 is the third row because the rows collection is zero-based). While that works, it can get difficult to work within a large string. You can change the second-to-last line to: ...

Get C# Database Basics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.