我有一个数据绑定的datagridview,其数据类为
public class Data
{
public int itemId { get; set; }
public int minAmount { get; set; }
public int maxAmount { get; set; }
public decimal rate { get; set; }
public string rarity { get; set; }
public bool announce { get; set; }
}
Dictionary<string, Data[]> Dict = new Dictionary<string, Data[]>();
private void button1_Click(object sender, EventArgs e)
{
string readText = File.ReadAllText(@"D:\Download\npc_drops.json");
var result = JsonConvert.DeserializeObject<Dictionary<string, Data[]>>(readText);
foreach (KeyValuePair<string, Data[]> entry in result)
{
Data[] dat = (Data[])entry.Value;
string npc = entry.Key;
listBox1.Items.Add(npc);
Dict.Add(npc, dat);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
BindingSource bs = (BindingSource)this.dataGridView1.DataSource;
this.dataGridView1.Rows.Clear();
string curItem = listBox1.SelectedItem.ToString();
Data[] data = Dict[curItem];
foreach (Data item in data)
{
bs.Add(item);
}
this.dataGridView1.DataSource = bs;
}
private void button2_Click(object sender, EventArgs e)
{
File.WriteAllText(@"D:\Download\npc_drops (1).json", string.Empty);
var result = JsonConvert.SerializeObject(Dict);
File.WriteAllText(@"D:\Download\npc_drops (1).json", result);
}
private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
string curItem = listBox1.SelectedItem.ToString();
// I'm trying to get all the rows of datagridView1 and change the Dict's data of the currently selected item to the data of datagridview1
}
基本上我正在尝试将行从datagridview放入数据数组 aka数据[]
使用WinForms,我没有使用数据库或其他任何东西,我只是反序列化json数据并将其添加到datagridview
答案 0 :(得分:0)
var bindingSource = (BindingSource)dataGridView1.DataSource;
BindingList<Data> list = new BindingList<Data>();
list = (BindingList < Data >)bindingSource.List;
Dict[curItem] = list.ToArray();
这解决了我的问题
答案 1 :(得分:0)
您可以通过将button3
的类型更改为Dict
并仅更新Dictionary<string, BindingList<Data>>
中的dataGridView1.DataSource
来完全消除listBox1_SelectedIndexChanged
。
private Dictionary<string, BindingList<Data>> Dict = new Dictionary<string, BindingList<Data>>();
private void button1_Click(object sender, EventArgs e)
{
string readText = File.ReadAllText(@"D:\Download\npc_drops.json");
Dict = JsonConvert.DeserializeObject<Dictionary<string, BindingList<Data>>>(readText);
foreach (var npc in Dict.Keys)
{
listBox1.Items.Add(npc);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string curItem = listBox1.SelectedItem.ToString();
dataGridView1.DataSource = Dict[curItem];
}
//button2_Click remains unchanged.
//button3 is removed from the form.