Currently I have a C# application which is reading in data from a table on my SQL Server database.
This is for end user purposes and management, I want them to be able to edit that data and commit it back to the database.
private void fillDataGrid()
{
string connectionString = "Server=; Database=; User Id=; Password=;";
DataTable Table = new DataTable("TestTable");
using (SqlConnection _con = new SqlConnection(connectionString))
{
string queryStatement = "SELECT * FROM dbo.table ORDER BY id ASC";
using (SqlCommand _cmd = new SqlCommand(queryStatement, _con))
{
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_con.Open();
_dap.Fill(Table);
_con.Close();
}
}
dataGridView1.DataSource = Table;
}
How do I commit the changes made through the app back to the server again?
Also, say I have a column called Colour
, is there a way I could specify the possible data for each row. IE rather than allow the user to type 'yellow', have red, yellow and blue as 'drop - down' options?
To commit changes to database, you have to specify InsertCommand, UpdateCommand and DeleteCommand of the adapter first.
May be helpful:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(v=vs.90).aspx
http://msdn.microsoft.com/en-us/library/ms254937(v=vs.90).aspx
Also, you can use DataGridViewComboBoxColumn (Beware of the null values in your Colour column, though, it does not handle nulls well)
// choose from existng:
var data = (from a in Table.AsEnumerable()
select new ValueHolder
{
Name = a.Field<string>("Colour")
}).Distinct().OrderBy(p => p.Name).ToList();
// your own
var data = new List<ValueHolder>();
data.Add(new ValueHolder("Red"));
data.Add(new ValueHolder("Yellow"));
//..................
var column = new DataGridViewComboBoxColumn();
column.DataSource = data;
column.ValueMember = "Name";
column.DisplayMember = "Name";
dataGridView1.Columns.Add(column);
//------------------------------------------------------------
class ValueHolder
{
public string Name{get;set;}
public ValueHolder(string name)
{
this.Name = name;
}
// this part may not be necessary without nulls:
//public override bool Equals(object obj)
// {
// ValueHolder other = obj as ValueHolder;
// if (other.Name.Equals(this.Name)) return true;
// return false;
// }
// public override int GetHashCode()
// {
// return Name == null ? 0 : Name.GetHashCode();
// }
}
it probably can be done in a simpler way, though.
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.