我想在DataGridView中执行搜索按钮。我使用以下代码读取了数据:
private void button1_Click_1(object sender, EventArgs e)
{
FileStream f1 = new FileStream("zapis.dat", FileMode.Open);
BinaryReader br = new BinaryReader(f1);
int а = 0;
while (f1.Position < f1.Length)
{
string data = br.ReadString();
string sing = br.ReadString();
string avtor = br.ReadString();
string zagl = br.ReadString();
string janr = br.ReadString();
string ezik = br.ReadString();
dataGridView1.Rows.Add(++а, ezik, zagl, avtor, janr, sing, data);
}
f1.Close();
}
我试图用代码做按钮:
private void textBox1_TextChanged(对象发送者,EventArgs e)
if (string.IsNullOrEmpty(textBox1.Text))
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
}
else
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", textBox1.Text);
}
}
但是当我开始时,出现错误: System.NullReferenceException:'对象引用未设置为对象的实例。'
(... as System.Data.DataTable) returned null.
上:
else
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", textBox1.Text);
我该如何解决?
答案 0 :(得分:0)
您没有将DataTable
用作DataGridView
的数据源。
使用一个类来表示您的数据,然后您就可以完成工作而无需使用“大量”的DataTable。
public class Item
{
public string Data { get; set; }
public string Sing { get; set; }
public string Avtor { get; set; }
// and so on ...
}
// Save data into private class member
private List<Item> _loadedData = new List<Item>();
private void button1_Click_1(object sender, EventArgs e)
{
using (var stream = new FileStream("zapis.dat", FileMode.Open))
using (var reader = new BinaryReader(stream))
{
var data = new List<Item>();
while (stream.Position < stream.length)
{
var item = new Item
{
Data = reader.ReadString(),
Sing = reader.ReadString(),
Avtor = reader.ReadString()
};
data.Add(item)
}
// update private member with newly loaded data
_loadedData = data;
}
// Bind loaded data to the DataGridView
datagridview1.DataSource = _loadedData;
}
可以使用简单的Where
方法对_loadedData
进行过滤。
private void textBox1_TextChanged(object sender, EventArgs e)
{
var filtered = _loadedData.Select(item => item);
if (string.IsNullOrEmpty(textBox1.Text) == false)
{
filtered = filtered.Where(item => item.Avtor == textBox1.Text);
}
datagridview1.DataSource = filtered.ToList();
}