今天完成了一个DEMO, XPtable直接增删改查,带富文本图片,这就是XPtable的优势。需要提示的是关于图片编辑后的保存:使用焦点,过滤掉逐条选择显示图片变化冗余保存数据库。
全部代码:
using System.Security.Policy;
using XPTable.Models;namespace XPTableUIDemo
{public partial class Form1 : Form{public Models.carContext db = new Models.carContext();public Form1(){InitializeComponent();xptable_display();}public static int i(object x1){return Convert.ToInt32(x1);}// 用户选择表格,读取对象,显示图片private void table1_SelectionChanged(object sender, XPTable.Events.SelectionEventArgs e){XPTable.Models.Row r = e.TableModel.Selections.SelectedItems.FirstOrDefault();var one = db.Materials.Where(c => c.id == (long)r.Cells[0].Data).FirstOrDefault();if (one.rtf != null){richTextBox1.Rtf = System.Text.Encoding.Default.GetString(one.rtf);}else{richTextBox1.Rtf = "";}}//改数据一个字段,保存一个对象private void table1_EditingStopped(object sender, XPTable.Events.CellEditEventArgs e){var one = db.Materials.Where(c => c.id == i(tableModel1.Rows[e.Row].Cells[0].Data)).FirstOrDefault();one.name = tableModel1.Rows[e.Row].Cells[1].Text;one.value = i(tableModel1.Rows[e.Row].Cells[2].Data);one.rtf = System.Text.Encoding.Default.GetBytes(richTextBox1.Rtf); db.SaveChanges();downtxt.Text = "数据已经保存!"; }//用户的焦点,在图片框改变图片,保存到数据库(使用焦点,过滤掉逐条选择显示图片变化)private void richTextBox1_TextChanged(object sender, EventArgs e){if (richTextBox1.Focused){XPTable.Models.Row r = tableModel1.Selections.SelectedItems.FirstOrDefault();var one = db.Materials.Where(c => c.id == (long)r.Cells[0].Data).FirstOrDefault(); one.rtf = System.Text.Encoding.Default.GetBytes(richTextBox1.Rtf); db.SaveChanges();downtxt.Text = r.Cells[0].Data.ToString() + " " + DateTime.Now.Ticks.ToString();}}//新增一条数据private void button1_Click(object sender, EventArgs e){db.Materials.Add(new Models.Material());db.SaveChanges();xptable_display();}//显示table数据private void xptable_display(){columnModel1.Columns.Clear();columnModel1.Columns.Add(new NumberColumn("ID", 50));columnModel1.Columns.Add(new TextColumn("名称", 150));columnModel1.Columns.Add(new NumberColumn("价格", 100));tableModel1.Rows.Clear();foreach (var item in db.Materials){XPTable.Models.Row r = new XPTable.Models.Row();tableModel1.Rows.Add(r);r.Cells.Add(new XPTable.Models.Cell(item.id));r.Cells.Add(new XPTable.Models.Cell(item.name));r.Cells.Add(new XPTable.Models.Cell(item.value));}}//删除一条数据private void button2_Click(object sender, EventArgs e){ DialogResult result = MessageBox.Show("确认要执行此操作吗?", "确认对话框", MessageBoxButtons.YesNo, MessageBoxIcon.Question);if (result == DialogResult.Yes){XPTable.Models.Row r = tableModel1.Selections.SelectedItems.FirstOrDefault();var one = db.Materials.Where(c => c.id == (long)r.Cells[0].Data).FirstOrDefault();if (one != null){db.Materials.Remove(one);db.SaveChanges();xptable_display();}}}}
}