【发布时间】:2014-08-20 14:29:31
【问题描述】:
布尔值用于在 SQL 数据库中经济地存储。但是在 C# 中使用数据源函数时的 datagridview 只是通过每行的复选框显示 true 或 false。
我想在 datagridview 中显示字符串值,而不是使用复选框的布尔值。
True = "旋转" 假=“元素” 如何将复选框更改为字符串值?
【问题讨论】:
标签: sql-server c#-4.0 boolean
布尔值用于在 SQL 数据库中经济地存储。但是在 C# 中使用数据源函数时的 datagridview 只是通过每行的复选框显示 true 或 false。
我想在 datagridview 中显示字符串值,而不是使用复选框的布尔值。
True = "旋转" 假=“元素” 如何将复选框更改为字符串值?
【问题讨论】:
标签: sql-server c#-4.0 boolean
你至少有两个选择来获得这个:
首先,您可以在RowDataBound 或GridView 期间更改绑定。看看this example,你有以下类:
public class Student
{
public int Roll { get; set; }
public string Name { get; set; }
public bool Status { get; set; }
}
你可以改变GridView的默认行为如下:
/// <summary>
/// Handles the RowDataBound event of the GridView2 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Student s = (Student)e.Row.DataItem;
if (s.Status == true)
{
e.Row.Cells[2].Text = "1";
}
else
{
e.Row.Cells[2].Text = "0";
}
}
}
解决此问题的另一种方法是使用custom formatting,根据您的需要处理CellFormatting 事件:
void gridView2_CellFormatting(object s, DataGridViewCellFormattingEventArgs evt)
{
if (evt.ColumnIndex == yourcolumnIndex){
if (evt.Value is bool){
evt.Value = ((bool)evt.Value) ? "Yes" : "No";
evt.FormattingApplied = true;
}
}
}
【讨论】:
使用Converter 可以让您轻松地做到这一点
using System;
using System.Windows.Data;
namespace WpfApplication2
{
[ValueConversion(typeof(Boolean), typeof(String))]
internal class BooleanToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Boolean state = (Boolean)value;
return state ? "Spin On" : "Element";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
然后,在您的 XAML 中,使用转换器将您的 String(我的示例中的标签)绑定到 Boolean(示例中的“状态”变量):
<Label Content="{Binding State, Converter={StaticResource BooleanToStringConverter }, Mode=OneWay}" />
【讨论】: