C# dataGridView 查詢/異動後,指回原資料列

  • 222
  • 0

C# dataGridView 查詢/異動後,指回原資料列

用變數ROWSINDEX、COLUMNSINDEX

在dataGridView1_SelectionChanged記錄目前的列數、行數

在查詢時再指向該列、該行

 

        int ROWSINDEX = 0;
        int COLUMNSINDEX = 0;
        
         private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow != null)
            {
                int rowindex = dataGridView1.CurrentRow.Index;
                if (rowindex >= 0)
                {
                    DataGridViewRow row = dataGridView1.Rows[rowindex];
                  

                    ROWSINDEX = dataGridView1.CurrentCell.RowIndex;
                    COLUMNSINDEX = dataGridView1.CurrentCell.ColumnIndex;

                    rowindex = ROWSINDEX;

                    ;
                }
                else
                {
                   

                }
            }
        }
        
        
        public void Search(string SDATES,string EDATES)
        {
            try
            {                
                SqlConnectionStringBuilder sqlsb = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["dbconn"].ConnectionString);             

                String connectionString;
                sqlConn = new SqlConnection(sqlsb.ConnectionString);


                sbSql.Clear();
                sbSqlQuery.Clear();


                sbSql.AppendFormat(@"  
                                    SELECT 
                                   
                                    *

                                    FROM [DB].[dbo].[TABLE]
                                    WHERE [SDATES]>='{0}' AND [EDATES]<='{1}'

                                    ", SDATES, EDATES);

                adapter = new SqlDataAdapter(@"" + sbSql, sqlConn);

                sqlCmdBuilder = new SqlCommandBuilder(adapter);
                sqlConn.Open();
                ds.Clear();
                adapter.Fill(ds, "TEMPds");
                sqlConn.Close();

                if (ds.Tables["TEMPds"].Rows.Count >= 1)
                {
                    //dataGridView1.Rows.Clear();
                    dataGridView1.DataSource = ds.Tables["TEMPds"];
                    dataGridView1.AutoResizeColumns();
                    //dataGridView1.CurrentCell = dataGridView1[0, rownum];

                    if (ROWSINDEX > 0 || COLUMNSINDEX > 0)
                    {
                        dataGridView1.CurrentCell = dataGridView1.Rows[ROWSINDEX].Cells[COLUMNSINDEX];

                        DataGridViewRow row = dataGridView1.Rows[ROWSINDEX];
                        textBox1.Text = row.Cells["ID"].Value.ToString();
                       
                    }
                }
                else
                {
                    dataGridView1.DataSource = null;
                }

            }
            catch
            {

            }
            finally
            {

            }
        }

 

 

 

 

自我LV~