WPF/C#: How to simplify the use of codes when calling a function (Generating Images)

Posted by eibhrum on Stack Overflow See other posts from Stack Overflow or by eibhrum
Published on 2010-04-30T10:44:35Z Indexed on 2010/04/30 10:47 UTC
Read the original article Hit count: 242

Filed under:
|
|
|
|

I created a function in one of my application that allows to generate an image (in WPF) by getting the 'source path' from the database that I am using:

    public void ShowImageThumb() 
    {
        try {
            cn = new MySqlConnection();
            cn.ConnectionString = ConfigurationManager.AppSettings["MyConnection"];
            cn.Open();
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = cn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT thumb FROM album WHERE thumbNo=1";
            MySqlDataAdapter adp = new MySqlDataAdapter();
            adp.SelectCommand = cmd;

            DataTable dt = new DataTable();
            adp.Fill(dt);
            MySqlDataReader r = cmd.ExecuteReader();
            while (r.Read())
            {
                BitmapImage bmi1 = new BitmapImage(new Uri(r[0].ToString(), UriKind.Relative));
                image1.Source = bmi1;

            }
            r.Close();
            cn.Close();

        }

        catch (Exception err){
            System.Windows.MessageBox.Show(err.Message);
        }

        finally { }

    }

Take a look on my SQL statement. I put a WHERE thumbNo=1 which allows the function to get 1 record. You see, I do have at least 10 records - file paths listed in that table.

I just wanna ask if there's a possible way to make my SQL statement something like this:

SELECT thumb FROM album;

while having this piece of code inserted in my function:

BitmapImage bmi2 = new BitmapImage(new Uri(r["second record?"].ToString(), UriKind.Relative));
                image2.Source = bmi2; //something like this

BitmapImage bmi3 = new BitmapImage(new Uri(r["third record?"].ToString(), UriKind.Relative));
                image3.Source = bmi3; //something like this

and so on and so forth, without ending up creating 10 different functions for 10 records.

ShowImageThumb2();
.
. // will not do this
.
ShowImageThumb10(); 

Sorry for the lengthy post. I hope somebody could answer back. Thanks!

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf