2012-06-22 21 views
0

我試圖編寫一段軟件,它將從MSSQL數據庫中取值,並將其放入DataGridView,Visual Studio的數據綁定功能爲完善。問題是,我想在數據庫進入控制之前格式化/處理數據庫中的信息。Windows窗體數據綁定 - 控制數據,然後再控制它

例如,在一個數據庫表中,我有一個名爲UserTypeID的項目,其中包含整數,另一個表格將UserTypeID映射爲像「Admin」,「Operator」,「Guest」等字符串UserType。我想成爲能夠從第一個表中獲取UserTypeID,通過第二個表將其轉換爲它的String等價物,然後將結果傳遞給DataGridView。

有沒有相當簡單的方法來做到這一點,或者是需要一箇中介對象或什麼的?

+0

你問如何進行具體操作,或者只是如何在普遍執行的操作,數據綁定之前打電話給你的價值觀? – Tyrsius

+0

@Tyrsius一般來說。這個具體的操作是我想要它做的一個例子。 – Abion47

+0

這其實很簡單。在將DataGridView的'DataSource'屬性設置爲任何持有數據的對象之前,請執行您需要的任何操作。 – Tyrsius

回答

0

如果字符串靜態的(將不添加/由用戶刪除),則最簡單的方式是創建一個列表<>或用於字符串的數組和這樣

string[] m = new string[] { "Guest", "Admin", "Operator", "Unit Manager", "User" } 

/// <summary> 
/// 
/// </summary> 
/// <param name="m">the string array which searches for the integer criteria.</param> 
/// <param name="s"> the int32 number which will pass to the index of the array </param> 
/// <returns></returns> 
public static string IntToString(this string S, string[] m, int s) 
{ 
    string z = m.ElementAt(s); 
    //Array.Clear(m, 0, m.Length); 

    /// if you will need to clear the string array elements each using of this method then delete the comment slashes in front of the Array.Clear() method 

    /// in Array.Clear method also -to depends of your need- you can disable to show the 
    /// Array elements.. May be you will need only 1 admin and if an admin chooosen you can delete this option by changing the parameters of Array.Clear() Method 

    return z; 
} 

的小延伸方法並在數據訪問層類簡單的使用例子:

string g; 

if (dataReader["yourIntValueFromTable"] != DBNull.Value) 
{       
    yourClassObject.yourIntValueFromTable = (int)dataReader["yourIntValueFromTable"]; 

    yourClassObject.yourStringValue = g.IntToString(m, ((int)dataReader["yourIntValueFromTable"])); 

} 

填充後,這個類可以作爲數據源設置爲任何你想要的。

但是,如果你的字符串是動態的,那麼你需要創建一個存儲過程,並從那裏

-1

從SQL執行必要的加入,包括在返回結果

SELECT u.userID, u.userName, u.userTypeID, ut.userTypeName 
FROM Users u 
JOIN UserType ut ON u.userTypeID = ut.userTypeID 

這就給了你,你在DataGridView需要額外的列必需的列。 如果您使用的是DataTable,它會很容易,因爲它可以包含可變數量的列。只是冰心數據表到您的datagridview

對於對象的集合,你將有額外的屬性:

class User 
{ 
    int UserTypeId { get; set; } 
    string UserTypeName { get; set; } // this could also be readonly depending on how you want it set 
} 
0

你可以做什麼@Tyrsius建議。但是,如果您使用一組對象作爲數據源,則可以在該屬性的GET方法中執行操作。那就是我會做的!