WinForms DataGridView - Updated Database

I know this is the main function of the DataGridView, but for some reason I just can't get it to work. I just want the DataGridView in my Windows form to post any changes made to the database when the user clicks the Save button.

I populate the DataGridView according to the function invoked by the user selection in DropDownList, as follows:

using (SqlConnection con = new SqlConnection(conString))
{
    con.Open();
    SqlDataAdapter ruleTableDA = new SqlDataAdapter("SELECT rule.fldFluteType AS [Flute], rule.fldKnife AS [Knife], rule.fldScore AS [Score], rule.fldLowKnife AS [Low Knife], rule.fldMatrixScore AS [Matrix Score], rule.fldMatrix AS [Matrix] FROM   dbo.tblRuleTypes rule WHERE rule.fldMachine_ID = '1003'", con);
    DataSet ruleTableDS = new DataSet();
    ruleTableDA.Fill(ruleTableDS);
    RuleTable.DataSource = ruleTableDS.Tables[0];
}

In my save function, I basically have the following (I cut off part of the code to get to the point):

using (SqlDataAdapter ruleTableDA = new SqlDataAdapter("SELECT rule.fldFluteType AS [Flute], rule.fldKnife AS [Knife], 
       rule.fldScore AS [Score], rule.fldLowKnife AS [Low Knife],
       rule.fldMatrixScore AS [Matrix Score], rule.fldMatrix AS [Matrix]
       FROM dbo.tblRuleTypes rule WHERE rule.fldMachine_ID = '1003'", con))
    {
        SqlCommandBuilder commandBuilder = new SqlCommandBuilder(ruleTableDA);
        DataTable dt = new DataTable();
        dt = RuleTable.DataSource as DataTable;
        ruleTableDA.Fill(dt);
        ruleTableDA.Update(dt);
    }

, , : , DataTable DataGridView (RuleTable), DataAdapter DataTable . ruleTableDA.Update(dt) "Concurrency : UpdateCommand 0 1 ".

+3
3

, : , , , /. , . , , , . , , , , , , , , . , SQLCommandBuilder , GetInsertCommand, GetUpdateCommand .., .

using (SqlDataAdapter ruleTableDA = new SqlDataAdapter("SELECT rule.fldFluteType AS [Flute], rule.fldKnife AS [Knife], 
       rule.fldScore AS [Score], rule.fldLowKnife AS [Low Knife],
       rule.fldMatrixScore AS [Matrix Score], rule.fldMatrix AS [Matrix]
       FROM dbo.tblRuleTypes rule WHERE rule.fldMachine_ID = '1003'", con))
    {
        SqlCommandBuilder commandBuilder = new SqlCommandBuilder(ruleTableDA);
        DataTable dt = new DataTable();
        dt = RuleTable.DataSource as DataTable;
        //ruleTableDA.Fill(dt);
        ruleTableDA.Update(dt);
    }
+5

MSDN , update/delete/insert , SelectCommand. , , SqlDataAdapter. SqlCommanduBuilder.

ruleTableDA.UpdateCommand = commandBuilder.GetUpdateCommand()
ruleTableDA.InsertCommand = commandBuilder.GetInsertCommand()
ruleTableDA.DeleteCommand = commandBuilder.GetDeleteCommand()
+2

You may need this to get the Refresh command.

ruleTableDA.UpdateCommand = commandBuilder.GetUpdateCommand();
0
source

Source: https://habr.com/ru/post/1740795/


All Articles