简体   繁体   中英

C# Visual Studio: How do I update a DB from Edit with DataGridView using LINQ?

I have a form WinForms form window with a DataGridView. It pulls data from a SQL Server Express database using Linq and displays it in the DataGridView columns properly. I have it set in the properties to allow editing. When I edit and change a field during runtime it will only update the database if I specify one column name. This doesn't work well because I need it to update the column I edit, not the one hard coded. It needs to be dynamic. See the comments next to site.??? I can choose a column name manually from site.whatever but that's not what I want. I want to be able to do Site.columnname from the string I set.

I see other examples loading and/or editing a DataGridView with data, but these examples are not using LINQ.

My form load code:

    public partial class EditImage : Form
    {
        SQL sqlLink = new SQL();
        CustomMessageBox msg = new CustomMessageBox();

    public EditImage()
    {
        InitializeComponent();
    }

    private void EditImage_Load(object sender, EventArgs e)
    {
        dgImageView.DataSource = sqlLink.getImageList();
        dgImageView.AutoResizeColumns();
        dgImageView.AutoResizeRows();
    }

    private void dgImageView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        int rid = e.RowIndex;
        int dbrid = rid + 1;
        int cid = e.ColumnIndex;
        string change = dgImageView[cid, rid].Value.ToString();
        string columname = dgImageView[cid, rid].OwningColumn.Name;

        using (var dc = new DbLink())
        {
            var site = (from img in dc.images where img.id == dbrid select img).SingleOrDefault();

            if (site != null)
            {
                try
                {
                    site.??? = change;
                    dc.SubmitChanges();
                    dgImageView.EndEdit();
                }
                catch (Exception ex)
                {
                    msg.Text("Error", ex.ToString(), MessageBoxButtons.OK);
                }
            }
        }
    }

Code from SQL class to retrieve DataSource:

    public IQueryable getImageList()
    {
        return selectImageList();
    }

and

    private IQueryable selectImageList()
    {
        DbLink dbl = new DbLink();
        image tl = new image();

        var results = from imgs in dbl.images
                      select imgs;

        return results;
    }

A screenshot of the dbml file:

在此处输入图片说明

You could try with reflection:

var changedColumn = typeof(image).GetProperty(columnName);
changedColumn.SetValue(site,change);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM