對於DataView
您需要做的就是將父DataTable
的CaseSensitive
屬性設置爲true。我只是快速原型與下面的代碼,它工作正常:
public Form1()
{
InitializeComponent();
DataSet set1 = new DataSet();
// Some xml data to populate the DataSet with.
string testXml =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<numbers>" +
"<number><name>one</name></number>" +
"<number><name>two</name></number>" +
"<number><name>Two</name></number>" +
"<number><name>three</name></number>" +
"</numbers>";
// Read the xml.
StringReader reader = new StringReader(testXml);
set1.ReadXml(reader);
// Get a DataView of the table contained in the dataset.
DataTableCollection tables = set1.Tables;
// Set the CaseSensetive property
tables[0].CaseSensitive = true;
DataView view1 = new DataView(tables[0]);
// Create a DataGridView control and add it to the form.
dataGridView1.AutoGenerateColumns = true;
// Create a BindingSource and set its DataSource property to
// the DataView.
BindingSource source1 = new BindingSource();
source1.DataSource = view1;
// Set the data source for the DataGridView.
dataGridView1.DataSource = source1;
// Set the Position property to the results of the Find method.
int itemFound = source1.Find("name", "Two");
source1.Position = itemFound;
}
對於需要其他類型的IBindingList的,作爲文檔說,它實現了一個查找區分大小寫的基礎列表。對於完整性我展示的代碼做下面這個樣子:
public Form1()
{
InitializeComponent();
// This uses my CaseSensitiveBindingList which I have code for later
BindingList<DGVItems> source = new CaseSensitiveBindingList<DGVItems>()
{
new DGVItems { Number = "one" },
new DGVItems{Number = "two"},
new DGVItems{Number = "Two"}
};
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = source;
dataGridView1.DataSource = bindingSource;
var index = bindingSource.Find("Number", "Two");
// Index is 2 (third item) as desired.
MessageBox.Show(number.ToString());
}
public class DGVItems
{
public string Number { get; set; }
}
而對於CaseSensitiveBindingList代碼:
public class CaseInsensitiveBindingList<T> : BindingList<T>
{
protected override int FindCore(PropertyDescriptor prop, object key)
{
string stringKey = key as string;
bool keyIsString = stringKey != null;
for (int i = 0; i < Count; ++i)
{
if (keyIsString && prop.PropertyType.IsAssignableFrom(typeof(string)))
{
if (stringKey.Equals(prop.GetValue(Items[i]).ToString(), StringComparison.CurrentCulture))
return i;
}
else
{
if (key.Equals(prop.GetValue(Items[i])))
return i;
}
}
return -1;
}
}
該代碼幾乎肯定能夠改善,但顯示的一般概念。
我仍然無法找到這個解決方案。在文檔之後稍微進一步:對於DataView(我相信它是我的基礎列表),它表示這稱爲IBindingList.Find。沒有關於這是否區分大小寫的說法,但是有一個創建具有自定義搜索的類的示例。 http://msdn.microsoft.com/en-us/library/system.componentmodel.ibindinglist.find.aspx 我希望我應該能夠使用此示例來創建DataView的自定義搜索,而不是大小寫敏感,但是,我不知道從哪裏開始。 任何人都可以提出一種方法嗎? – shindigo 2010-04-20 13:30:37