Windows窗体数据绑定 - 在控制之前处理数据

时间:2012-06-22 23:11:26

标签: c# sql-server database winforms data-binding

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

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

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

3 个答案:

答案 0 :(得分:0)

你可以做@Tyrsius建议的事情。但是,如果您使用对象集合作为数据源,则可以在GET方法中对该属性进行操作。多数民众赞成我会做的!

答案 1 :(得分:0)

如果字符串是静态的(不会被用户添加/删除),那么最简单的方法是创建一个List<>或字符串的数组和像这样的小扩展方法

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"]));

}
填写此类后,您可以将数据源设置为您想要的任何位置。

但是,如果您的字符串是动态的,那么您需要创建一个存储过程并从那里调用您的值

答案 2 :(得分:-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
}