簡體   English   中英

如何從C#中的數據庫獲取值作為鍵/值對

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

我正在嘗試向我的第一個WPF應用程序中顯示一個餅圖。現在,按照我的開始,我已經從本地數據中測試了餅圖,並且在WPF中可以正常工作了。現在,根據我的要求,我必須用數據替換本地數據從數據庫中,但我無法找到如何實現的方法。這是我的本地數據功能。

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) };
    }

我的數據庫表中有相同類型的數據。我正在使用MySql。

怎么樣:

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();
}

現在只用適合您的數據庫的SQL填充此示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM