Click here to Skip to main content
15,893,814 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a problem in my code about search after connecting to a database with MSSQL. The idea was to edit the database (add,update,delete) and also to search the database. With the edit i'm ok but with the search i can't do anything. I don't know even how to start. The database has two columns, one with numbers and the other is text.

Sorry for my english and thank you very much.
Posted

Firstly, this part of your code seems to be unnecessary:
C#
foreach (DataColumn dc in userTable.Columns)
{
      DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
      column.DataPropertyName = dc.ColumnName;
      column.HeaderText = dc.ColumnName;
      column.Name = dc.ColumnName;
      column.SortMode = DataGridViewColumnSortMode.Automatic;
      column.ValueType = dc.DataType;
      userDataGridView.Columns.Add(column);
}


because you are using all of the columns from userTable. If you only wanted a few of them, then that would be a reasonable way to do it. The DataGridView will automatically add the columns for you, unless you have set its <code>AutoGenerateColumns property to false.

Secondly, your code does not show where the DataGridview has its DataSource property set (except near the top, where it is set to null).

Still, wherever that is done try this.
Add a BindingSource component to your form, (for the purpose of this explanation I'll call it userBindingSource). In the designer, set the DataSource for your DataGridView to this new userBindingSource. From here on you will never change this, all future changes will be done to userBindingSource.

Then wherever in your code you set the DataSource property of userDataGridView, e.g.
C#
userDataGridView.DataSource = null;

// OR
userDataGridView.DataSource = userTable;


change those to:
C#
userBindingSource.DataSource = null;

// AND
userBindingSource.DataSource = userTable;


Make sure that you change all of them, otherwise it won't work.

Then, assuming that your application still works as it does now, you will be able to use the BindingSource.Find[^] method to locate the index of the row, and set CurrentRow for the DataGridView to that index.

BindingSource also has MoveFirst, MoveLast, MoveNext and MovePrevious methods which will fit the buttons that you have in your app.
 
Share this answer
 
Here are a couple of really good links for starters:


1.[^]

2.[^]
 
Share this answer
 
v2
Thank you very much for your answer, but these articles can not help me. They refer at "how to connect,edit,delete,update" and i already have done these. I have a problem with the search through the database and i can not find anywhere an article that explains how to do it.
 
Share this answer
 
i implemented search basing on the column
ie the user has to select the particular column and enter the text in the searchbox , on search button click i searched the particular datatable's column with the text entered in the searchbox .

if you are trying to implement something like this i have the code for it . let me know i used the objectdatasource as my datasource, anyways it would be the same but if you use other datasource then you can search in the dataview itself.
 
Share this answer
 
Yes,exactrly that i want. I've made two radiobuttons for the user to select how he want to search (by code or by description).
Thank you very much
 
Share this answer
 
Take a look at this[^] article here on Code Project. It may help.

Although that article shows how to return a DataSet from your Database which you could use as the DataSource of your DataGrid(View) (Incidentally you do not say if this is WindowsForms, ASP or what, so I do not know what type of grid you are talking about.)

You could also use DataView.Filter (search on MSDN for good examples) which would limit the DataGrid to just showing matching records.

If on the other hand you want to retain all displayed records and just scroll to the one with the users choice then one way might be to use the <code>BindingSource.Find method (Example[^]), assuming you are using a BindingSource, of course.
 
Share this answer
 
Sorry for that, is a WindowsForms and here is the code which i make the connection with the database.
C#
private void btnLoad_Click(object sender, EventArgs e)
        {
            lblLoadedTable.Text = "Read data from" + cmbTables.Text.Trim();
            btnLoad.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            try
            {
                if (userTable != null)
                {
                    userTable.Clear();
                }
                userDataGridView.DataSource = null;                
                userDataGridView.Rows.Clear();
                userDataGridView.Refresh();
                sqlQuery = "SELECT * FROM [" + cmbTables.Text.Trim() + "]";
                SetDataObjects();
                connection.Open();
                ticker.Start();
                adapter.Fill(tempDataSet);
                totalRecords = tempDataSet.Tables[0].Rows.Count;
                tempDataSet.Clear();
                tempDataSet.Dispose();
                adapter.Fill(ds, 0, 5, cmbTables.Text.Trim());
                userTable = ds.Tables[cmbTables.Text.Trim()];                                
                                
                foreach (DataColumn dc in userTable.Columns)
                {
                    DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
                    column.DataPropertyName = dc.ColumnName;
                    column.HeaderText = dc.ColumnName;
                    column.Name = dc.ColumnName;                    
                    column.SortMode = DataGridViewColumnSortMode.Automatic;
                    column.ValueType = dc.DataType;                    
                    userDataGridView.Columns.Add(column);
                }
                lblLoadedTable.Text = "Data loaded from " + userTable.TableName;
                lblTotRecords.Text = "Total records" + totalRecords;
                CreateTempTable(0, int.Parse(cmbNoOfRecords.Text.Trim()));                
                                
                btnPrevious.Enabled = true;
                btnFirst.Enabled = true;
                btnPrevious.Enabled = true;
                btnNext.Enabled = true;
                btnLast.Enabled = true;
                btnAdd.Enabled = true;
                btnUpdate.Enabled = true;
                btnDelete.Enabled = true;
                cmbNoOfRecords.Enabled = true;                
            }
            catch (Exception ex)
            {                
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                connection.Close();
                btnLoad.Enabled = true;
                this.Cursor = Cursors.Default;
                prgProgress.Value = 0;                
                prgProgress.Update();
                prgProgress.Refresh();
                ticker.Stop();
            }
        }
 
Share this answer
 
v2
Thank you very much...That was very helpful. I was searching for this a lot time!!!!
 
Share this answer
 
C#
private void button2_Click(object sender, EventArgs e)
      {
          if (rbcode.Checked)
          {
              if (this.findTextBox1.Text.Length > 0)
            {
                int loc = bindingSource1.Find("CODE", this.findTextBox1.Text);
              if (loc == -1)
              {
                  DataView dv = new DataView(this.userTable);
                  dv.RowFilter = string.Format("CODE LIKE '{0}*'", this.findTextBox1.Text);
                  if (dv.Count > 0)
                  {
                      loc = bindingSource1.Find("CODE", dv[0]["CODE"]);
                  }
              }
              bindingSource1.Position = loc;
            }
          }
  }


So far so good,but i want every time i hit the search button to show me the next result...Any ideas?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900