问题
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:
回答1:
You could try with reflection:
var changedColumn = typeof(image).GetProperty(columnName);
changedColumn.SetValue(site,change);
来源:https://stackoverflow.com/questions/37925687/c-sharp-visual-studio-how-do-i-update-a-db-from-edit-with-datagridview-using-li