C# Windows窗体数据绑定-在将数据交给控件之前对其进行操作

C# Windows窗体数据绑定-在将数据交给控件之前对其进行操作,c#,sql-server,database,winforms,data-binding,C#,Sql Server,Database,Winforms,Data Binding,我正在尝试编写一个软件,它将从MSSQL数据库中获取值,并将其放入DataGridView中,VisualStudio的数据绑定功能对于DataGridView来说是完美的。问题是我想在数据库中的信息到达控件之前对其进行格式化/操作 例如,在一个数据库表中,我有一个名为UserTypeID的条目,其中包含整数,而另一个表将UserTypeID映射为字符串UserType,如“Admin”、“Operator”、“Guest”等。我希望能够从第一个表中获取UserTypeID,通过第二个表将其转换

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

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


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

从SQL执行必要的联接,并在返回的结果中包含必要的列

SELECT u.userID, u.userName, u.userTypeID, ut.userTypeName
FROM Users u
JOIN UserType ut ON u.userTypeID = ut.userTypeID
这为您提供了datagridview中所需的额外列。 如果您使用的是DataTable,这将很容易,因为它可以包含可变数量的列。只需将datatable bing到datagridview

对于对象集合,您将具有额外的属性:

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

你可以按照@Tyrsius的建议去做。但是,如果使用对象集合作为数据源,则可以在GET方法中对该属性进行操作。那就是我要做的

如果字符串是静态的(用户不会添加/删除),那么最简单的方法就是为字符串创建一个列表或数组,并创建一个类似这样的小扩展方法

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;
} 
填充该类后,您可以将其设置为数据源,并将其设置到您想要的任何位置


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

在数据绑定之前,您是在询问如何执行特定的操作,还是仅仅询问如何执行一般的操作?@Tyrsius。这个特定的操作就是我想要它做的一个例子。这实际上很简单。在将
DataGridView
DataSource
属性设置为保存数据的任何对象之前,请执行您需要的任何操作。@Tyrsius您是说以编程方式分配数据源吗?如果是这样的话,我是否需要第二个数据源来保存新的/被操纵的值以提供给DataGridView?我说的是以编程方式分配数据源。这样做不需要第二个数据源。除非您在
dataAdapter
中进行这些操作,否则您将需要以编程方式进行操作。
string g;

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

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

}