Boolean用于经济地存储在SQL数据库中。但是在C#中使用数据源函数时的datagridview只是通过每行的复选框显示true或false。
我想在datagridview中显示字符串值,而不是使用复选框显示布尔值。
True =" Spin On" 假="元素" 如何将复选框更改为字符串值?
答案 0 :(得分:0)
您至少有两种方法可以获得此选项:
首先,您可以在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;
}
}
}
答案 1 :(得分:0)
使用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
(示例中的状态&#39;变量):
<Label Content="{Binding State, Converter={StaticResource BooleanToStringConverter }, Mode=OneWay}" />