简体   繁体   中英

How to take values as Key/value pair from database in C#

I am trying to show a pie chart into my First WPF application.Now as per my starting i have tested the pie chart from the Local data and its working fine in WPF.Now as per my requirement i have to replace local data with the data from the database but i am not able to find out how to achieve it.. Here is my local data function..

private void LoadPieChartData()
    {
        ((PieSeries)mcChart.Series[0]).ItemsSource =
            new KeyValuePair<string, int>[]{
        new KeyValuePair<string, int>("Project Manager", 12),
        new KeyValuePair<string, int>("CEO", 25),
        new KeyValuePair<string, int>("Software Engg.", 5),
        new KeyValuePair<string, int>("Team Leader", 6),
        new KeyValuePair<string, int>("Project Leader", 10),
        new KeyValuePair<string, int>("Developer", 4) };
    }

I have the same type of data in my database table..I am using MySql..

How about:

private KeyValuePair<string, int>[] GetData()
{
SqlConnection conn = new SqlConnection("connectionstring");
SqlCommand comm = new SqlCommand("SELECT column1, column2 FROM mytable");

conn.Open();

try
{
    SqlDataReader sr = comm.ExecuteReader();
    IList<KeyValuePair<string, int>> returnColl = new List<KeyValuePair<string, int>>();
    if (sr.HasRows)
    {
        while(sr.Read())
        {
            returnColl.Add(new KeyValuePair<string, int>(sr["column1"].ToString(), sr["column2"]));
        }
    }
}
finally
{
    conn.Close();
}

return returnColl.ToArray();
}

now just fill this example with your SQL fitted to your database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM