0

我正在尝试编写一个软件,它将从 MSSQL 数据库中获取值并将其放入 DataGridView,Visual Studio 的数据绑定功能非常适合。问题是我想在数据库中的信息到达控件之前对其进行格式化/操作。

例如,在一个数据库表中,我有一个名为 UserTypeID 的条目,其中包含整数,而另一个表将 UserTypeID 映射为字符串 UserType,例如“Admin”、“Operator”、“Guest”等。我希望能够获取来自第一个表的 UserTypeID,通过第二个表将其转换为等效的字符串,然后将结果传递给 DataGridView。

有没有一种相当简单的方法可以做到这一点,或者需要一个中间对象或其他什么?

4

3 回答 3

0

You can do what @Tyrsius suggested. But,if you are using a collection of objects as your datasource, you can do the manipulations in the GET method for that property. Thats what I would do!

于 2012-06-22T23:42:19.407 回答
0

if the strings are static (will not add / delete by the user ) then the easiest way is to create a List<> or an array for the strings and a small extension method like this

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

and a simple usage example in a Data Access Layer class :

string g;

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

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

}

after fill this class you can set as datasource to wherever you want.

but, if your strings are dynamic then you need to create a Stored Proc and call your values from there

于 2012-06-22T23:43:40.500 回答
-1

From your SQL perform the necessary join and include the necessary columns in the returned result

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

That gives you the extra columns you need in the datagridview. If you are using DataTable this would be easy as it can contain variable number of columns. Just bing the datatable to your datagridview

For collection of objects, you will have extra properties:

class User
{
    int UserTypeId { get; set; }
    string UserTypeName { get; set; } // this could also be readonly depending on how you want it set
}
于 2012-06-22T23:36:32.467 回答