Answered runtime select item of combobox

  • Friday, February 03, 2012 11:42 PM
     
      Has Code

    Hi all,

    Im writing a sqlite database application. I got datagridview in my form and some textboxes and couple of comboxes to view, add or edit rows in datagridview. And thats the point, i want to select item from comboboxes on dataGridView1_RowStateChanged, but dont know how.

    my combobox is filled up with these lines

    string select4 = "select * from LV";
    data2 = new SQLiteDataAdapter(select4, asd2);
    data2.Fill(dataSet3);
    comboBox2.DataSource = dataSet3.Tables[0].DefaultView;
    comboBox2.DisplayMember = "nazov";
    comboBox2.ValueMember = "idlv";
    

     

    i think it should be something like this

    comboBox2.SelectedItem = dataGridView1.SelectedRows[0].Cells[2].Value;

    or

    comboBox2.SelectedIndex = dataSet3.Tables[0].Rows.IndexOf(dataGridView1.SelectedRows[0].Cells[2].Value.ToString());

     

    but none of that works. Thanks for any answer, Ondro

    • Moved by Rudedog2MVP Saturday, February 04, 2012 12:29 AM : move to more appropriate forum : (From:Visual C# General)
    •  

All Replies

  • Saturday, February 04, 2012 12:41 AM
     
      Has Code

    Hi Ondro Tadanai ml,
    Because you are binding to the DefaultView, you need to provide a value from the default view. eg.

     

    // Set the selected item to the first row in the first table
    comboBox2.SelectedItem = dataSet3.Tables[0].DefaultView[0];
    

    You can also do

     

    comboBox2.SelectedIndex = comboBox2.Items.IndexOf(ds.Tables[0].DefaultView[0]);
    

     


    Currently developing FaultTrack. I occassionally blog about C# and .NET.
    Hoping to become a MVP by 2013. Email: danderson [at] dcomproductions [dot] com

  • Saturday, February 04, 2012 1:07 AM
     
      Has Code

    Hello Ondro Tadanai ml,

    I do not have an example for your database provider or in C# but the example demostrates binding the two controls together on a key, in this case a customer identifier. If you need the database you can download it here, it is the Microsoft NorthWind database The idea is to add a DataBinding to the ComboBox (see example below)

    Add a DataGridView called DataGridView1 and a ComboBox named cboCompanyList to a form in a VB.NET project, add the code below, created a folder named Data under the Debug folder, build the project, run the project followed by traversing the DataGridView row and the ComboBox will track what you do in the DataGridView.

    VS2010 code

    Public Class Form1
        WithEvents Master As New BindingSource()
        Public ReadOnly Property bsMaster() As BindingSource
            Get
                Return Master
            End Get
        End Property
        Private DatabaseFileName As String = "data\nwind.mdb"
        Public ReadOnly Property ConnectionString() As String
            Get
                Return _
                <Connection>
                    Provider=Microsoft.Jet.OLEDB.4.0;
                    Data Source=<%= DatabaseFileName %>;
                    Persist Security Info=False
                </Connection>.Value
            End Get
        End Property
        Public Sub LoadDataGridViews()
            Using cn As New OleDbConnection(ConnectionString)
    
                cn.Open()
                LoadCompaniesIntoComboBox(cn)
    
                Dim cmd As New OleDb.OleDbCommand(
                    <SQL>
                        SELECT 
                            CustomerID, 
                            CompanyName, 
                            Address, 
                            City, 
                            PostalCode, 
                            Phone 
                        FROM 
                            Customers 
                        ORDER BY 
                            CompanyName
                    </SQL>.Value,
                cn)
    
                Dim dt As New DataTable
    
                dt.Load(cmd.ExecuteReader)
                bsMaster.DataSource = dt
            End Using
    
            DataGridView1.DataSource = bsMaster
    
            cboCompanyList.DataBindings.Add("SelectedValue", bsMaster, "CustomerID")
        End Sub
        Public Sub LoadCompaniesIntoComboBox(ByVal cn As OleDbConnection)
            Dim cmd As New OleDbCommand("SELECT CustomerID, CompanyName From Customers", cn)
            Dim dt As New DataTable
            dt.Load(cmd.ExecuteReader)
    
            cboCompanyList.DisplayMember = "CompanyName"
            cboCompanyList.ValueMember = "CustomerID"
            cboCompanyList.DataSource = dt
        End Sub
        Private Sub Form1_Load(
            ByVal sender As System.Object,
            ByVal e As System.EventArgs) Handles MyBase.Load
    
            LoadDataGridViews()
    
        End Sub
    End Class
    
    

     


    KSG
  • Saturday, February 04, 2012 6:48 AM
     
     

    Thanks for answer

    but is there any possibility to select that item from only string from datagridview cell? Or search index of string in dataset?

     

     

     

    edit:

    comboBox2.SelectedItem = dataSet3.Tables[0].DefaultView[1];    throws error

    System.IndexOutOfRangeException was unhandled
    Message="Cannot find table 0."
     
    but as i write above there is a table 0

    string select4 = "select * from LV";
    data2 = new SQLiteDataAdapter(select4, asd2);
    data2.Fill(dataSet3);
    comboBox2.DataSource = dataSet3.Tables[0].DefaultView;
    comboBox2.DisplayMember = "nazov";
    comboBox2.ValueMember = "idlv";   

    in form load method

     

    edit2:

    the error was my fail, i declare dataset in form_create instead of constructor of class,

    so "comboBox2.SelectedItem = dataSet3.Tables[0].DefaultView[1];" is working but still dont know hot to select

    the one item which is selected in datagridview


  • Sunday, February 05, 2012 9:27 AM
     
     

    Can you provide the segment of code that binds your DataGridView to your DataSet? (I am assuming it is infact data bound to the dataset). You can implement some mechanism where when the DataGridView has a row selected, it searches for the item in the dataset (dataSet3) and selects it. There's a few different ways you can do what you want, but I would need to know how you are data binding your DataGridView before I can suggest my recommended approach.


    Currently developing FaultTrack. I occassionally blog about C# and .NET.
    Hoping to become a MVP by 2013. Email: danderson [at] dcomproductions [dot] com
  • Sunday, February 05, 2012 5:30 PM
     
     Answered Has Code

    If I'm not misunderstanding the question, I think all you need to do is databind your ComboBox to the same DataTable that your grid is bound to:

    -- grid databinding
    MyGrid.DataSource = MyDataSet.Tables[0];
    
    -- combo databinding
    comboBox2.DataSource = dataSet3.Tables[0].DefaultView;
    comboBox2.DisplayMember = "nazov";
    comboBox2.ValueMember = "idlv";   
    
    -- and the important part:
    comboBox2.DataBindings.Add("SelectedValue", MyDataSet.Tables[0]", "id");
    -- just guessed on the column name
    

     


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
  • Sunday, February 05, 2012 5:35 PM
     
      Has Code

    So as not to mess up the formatting in my previous reply (which an edit tends to do when there's a block of code), I'll just add the edit here: 

    The DataSource for the ComboBox doesn't have to be the DefaultView ... a DataBound object always respects the DefaultView and you should actually use the DataTable.  I meant to change the code that I copied from your post, but hit Submit before I remembered.

    comboBox2.DataSource = dataSet3.Tables[0];
    
    

    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
  • Thursday, February 09, 2012 11:04 AM
     
     
    thanks BonnieB, that helps me a lot, but i found solution some days ago. Its not so nice and clear, but works. I add invisible column idlv to the datagridview and im selecting an item of combobox from that cell
  • Thursday, February 09, 2012 3:37 PM
     
     
    Well, ok, I guess that would work too ... but the really correct way is to bind the ComboBox as I showed. It's much cleaner and simpler.

    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Friday, April 13, 2012 4:57 PM
     
     

    Hi,

    I would like to fill a textBox with value of combobox selected item,

    I explain, I have: 

    adresse

    latitude

    longitude

    in my combobox I have the adress, and i want if i choose one the latitude and the longitude display on the 2 textbox

    Any Idea?

  • Saturday, April 14, 2012 3:34 PM
     
      Has Code

    You probably should have started a separate thread, but I'll go ahead and give you a quickie answer. Of course, part of the answer depends on where your data is. I'm going to assume it's a DataTable. If so, you can do something like this:

    // if your table is in a DataSet
    DataTable MyTable = MyDataSet.Tables["MyTable"];
    cboAddress.DataSource = MyTable;
    cboAddress.DisplayMember = "address";
    txtLatitude.DataBindings.Add(MyTable, "latitude");
    txtLongitude.DataBindings.Add(MyTable, "longitude");
    If my assumptions about your use of a DataTable is incorrect, then please post whatever code you've got or have already tried.

    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Saturday, April 14, 2012 4:27 PM
     
      Has Code

    Thank you for your reply,

    yes i use the dataTable, 

    And i want when i select the adress in combobox, I display the latitude and longitude corresponding to this adress on textboxes.

    So, I add what you're suggested and it works fine, thank you, I share the code:

    private void button1_Click(object sender, EventArgs e) { string SQL = "SELECT * FROM CoordonneeCamera"; SQLiteCommand cmd = new SQLiteCommand(SQL); cmd.Connection = sqliteconnection1; SQLiteDataAdapter data = new SQLiteDataAdapter(cmd); DataSet ds = new DataSet(); try { data.Fill(ds, "Coordonnee"); DataTable dt = ds.Tables[0]; dataGridView1.DataSource = dt; comboBox2.DataSource = dt; comboBox2.DisplayMember = "adress";

    txtBoxLgtAdd.DataBindings.Add("text", dt, "Lgt");
                    txtBoxLatAdd.DataBindings.Add("text", dt, "Lat");

    } catch { } finally { cmd.Dispose(); sqliteconnection1.Close(); } }


    • Edited by Ostorlabi Saturday, April 14, 2012 4:43 PM
    •  
  • Saturday, April 14, 2012 4:58 PM
     
     

    Ooops, I realized that I showed the DataBindings.Add syntax incorrectly (I forgot to include "Text" ... I was just typing if off the top of my head). You've got the correct syntax, so that's good.

    I'm glad I could help out and that you got it to work!


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Monday, April 16, 2012 9:25 AM
     
      Has Code

    Thanks Bonnie :)

    if i want to add in my function parameters the latitude and longitude.

    public void addAdress(double lat, double lgt, string cam) { } public void displayCamIcon() { addAdress(lat, lgt, adress1); ex: addAdress(48.2690809, 4.0670811, "cam1"); }

    how could I fill the variable "double lat" from the myDatatable?

    thanks again


  • Monday, April 16, 2012 4:02 PM
     
      Has Code

    We can use the BindingContext Position property. When an item it chosen from the ComboBox, the Position property will point to the correct row in the DataTable, so something like this should do it:

    // You'll need to declare your DataSet as a member of your Form
    // instead of it being local to your DataAccess
    public void displayCamIcon()
    {
        DataTable dt = ds.Tables[0]; // for convenience   
        int i = this.BindingContext[dt].Position;
        addAdress(dt[i]["lat"], dt[i]["lgt"], dt[i]["adress"]);
    }


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Monday, April 16, 2012 4:42 PM
     
      Has Code

    Thank you for replying,

     addAdress(dt[i]["lat"], dt[i]["lgt"], dt[i]["adress"]); // the parameters: lat and long are double

    show me an error: 

    Error 3 Cannot apply indexing with [] to an expression of type 'System.Data.DataTable'

    • Edited by Ostorlabi Monday, April 16, 2012 4:50 PM
    •  
  • Monday, April 16, 2012 4:47 PM
     
      Has Code

    Oh sorry ... I'm too used to using Typed DataSet syntax, I should know better though. I should have written it this way:

    addAdress(dt.Rows[i]["lat"], dt.Rows[i]["lgt"], dt.Rows[i]["adress"]);


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Monday, April 16, 2012 4:59 PM
     
     

    I tried it also and it give me error

    Error 4 Argument 1: cannot convert from 'object' to 'double'

    Idon't know how to thread it?

  • Monday, April 16, 2012 5:03 PM
     
     
    Use either the Double.TryParse or the Convert.ToDouble to convert the data to the correct format before passing it to your addAdress method.

    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Monday, April 16, 2012 5:48 PM
     
     

    thank this is work:

    Convert.ToDouble(dt.Rows[i]["CameraLat"]), Convert.ToDouble(dt.Rows[i]["CameraLgt"])

    But there is something strange, when I change in the combobox, the value still the same, i tested it by 

     MessageBox.Show(latitude.ToString());

  • Monday, April 16, 2012 7:41 PM
     
     
    But where are you testing that code? And where are you calling the displayCamIcon() method? I guess I should have mentioned this (but figured that you already were aware of it), that your displayCamIcon() method should be called from the ComboBox's SelectedIndexChanged event handler. That way, every time a different item is chosen from the Combo, the new item's information will be evaluated by your displayCamIcon() method.

    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Tuesday, April 17, 2012 7:22 AM
     
      Has Code

    That is axactly what I did, the item change in the combobox but the information not,

    this is my code:

    Fill combobox:

    private void button18_Click(object sender, EventArgs e)
          {
              SQLiteConnection sqliteconnection1 = new SQLiteConnection(@"data source=C:\Users\Administrateur\Documents\Visual Studio 2010\Projects\GoogleMap_Videosurveillance\coordCamera.db3");
              string SQL = "SELECT * FROM CoordonneeCamera";
              SQLiteCommand cmd = new SQLiteCommand(SQL);
              cmd.Connection = sqliteconnection1;
              SQLiteDataAdapter data = new SQLiteDataAdapter(cmd);
    
              DataSet ds = new DataSet();
    
    
              data.Fill(ds, "CoordonneeCamera");
              DataTable dt = ds.Tables[0];
              comboBox1.DataSource = dt;
              comboBox1.DisplayMember = "CameraName";                        
          }

    Function DisplayCamIcon

    public void DisplayCamIcon()
          {
              SQLiteConnection sqliteconnection1 = new SQLiteConnection(@"data source=C:\Users\Administrateur\Documents\Visual Studio 2010\Projects\GoogleMap_Videosurveillance\coordCamera.db3");
              string SQL = "SELECT * FROM CoordonneeCamera";
              SQLiteCommand cmd = new SQLiteCommand(SQL);
              cmd.Connection = sqliteconnection1;
              SQLiteDataAdapter data = new SQLiteDataAdapter(cmd);
              DataSet ds = new DataSet();
              data.Fill(ds, "CoordonneeCamera");
              DataTable dt = ds.Tables[0];     
              int i = this.BindingContext[dt].Position;
              MainMap.Position = new PointLatLng(Convert.ToDouble(dt.Rows[i]["CameraLat"]), Convert.ToDouble(dt.Rows[i]["CameraLgt"]));
              latitude = Convert.ToDouble(dt.Rows[i]["CameraLat"]);
              longitude = Convert.ToDouble(dt.Rows[i]["CameraLgt"]);
          }

    And finallly I call this function in comboBox1_SelectedIndexChanged

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
          {
              
              MessageBox.Show(latitude.ToString());
              DisplayCamIcon();          
          }

    The message box show every time the value of the first Item! the index i is always "0".


    • Edited by Ostorlabi Tuesday, April 17, 2012 7:53 AM
    •  
  • Tuesday, April 17, 2012 2:34 PM
     
      Has Code

    You're overwriting your DataSet every time you call DisplayCamIcon() ... so of course the BindingContext .Position is always going to be 0. You are no longer in sync with the ComboBox's DataSource.

    What you need to do is declare your DataSet as a member of the Form, not inside each method call. In other word,s the DataSet needs to be scoped to the form, not local to each method. Your DisplayCamIcon() should not re-fill the DataSet. So your code becomes this:

    At the top of your Form with the rest of the declarations:

    private DataSet ds;

    Fill the Combo (although I imagine in your real app you wouldn't be doing this from a button click --- perhaps call a method from the Form Load event handler would be better:

    private void button18_Click(object sender, EventArgs e)
    {
      SQLiteConnection sqliteconnection1 = new SQLiteConnection(@"data source=C:\Users\Administrateur\Documents\Visual Studio 2010\Projects\GoogleMap_Videosurveillance\coordCamera.db3");
      string SQL = "SELECT * FROM CoordonneeCamera";
      SQLiteCommand cmd = new SQLiteCommand(SQL);
      cmd.Connection = sqliteconnection1;
      SQLiteDataAdapter data = new SQLiteDataAdapter(cmd);
      this.ds = new DataSet();
      data.Fill(this.ds, "CoordonneeCamera");
      DataTable dt = this.ds.Tables[0];
      comboBox1.DataSource = dt;
      comboBox1.DisplayMember = "CameraName";                        
    }

    And now your DisplayCamIcon() method becomes this:

    public void DisplayCamIcon()
    {
      DataTable dt = this.ds.Tables[0];     
      int i = this.BindingContext[dt].Position;
      MainMap.Position = new PointLatLng(Convert.ToDouble(dt.Rows[i]["CameraLat"]), Convert.ToDouble(dt.Rows[i]["CameraLgt"]));
      latitude = Convert.ToDouble(dt.Rows[i]["CameraLat"]);
      longitude = Convert.ToDouble(dt.Rows[i]["CameraLgt"]);
    }

    Does this make a lot more sense to you now?

    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Tuesday, April 17, 2012 3:36 PM
     
     
    Thanks again Bonnie :)

    But i still have a small problem, the first & second items have both index 0.

    i noted that before selecting the items in the combobox, it shows me messageShow "index 0" and also on selecting the second item and the third has index 1. 

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
          {
              
              MessageBox.Show(latitude.ToString());
              DisplayCamIcon();          
          }   
  • Tuesday, April 17, 2012 3:49 PM
     
      Has Code

    I'm not sure what you're using that shows "index 0" ... certainly not that MessageBox.Show(latitude.ToString()) .... that's got nothing to do with the index

    I guess one thing you could change in the SelectedIndexChanged handler is to wrap it up in an if checking that SelectedIndex is > -1.

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.comboBox1.SelectedIndex > -1)
        {
            //MessageBox.Show(latitude.ToString());
            DisplayCamIcon();          
        }
    }  

    I'm not sure what else to tell you ... are you debugging and that's where you see what the index is?


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Tuesday, April 17, 2012 4:01 PM
     
      Has Code

    Sorry, this is what i use:

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
                            
                DataTable dt = ds.Tables[0];            
                int i = this.BindingContext[dt].Position;
                MessageBox.Show(i.ToString());
                gMapControl1.Position = new PointLatLng(Convert.ToDouble(dt.Rows[i]["CameraLat"]), Convert.ToDouble(dt.Rows[i]["CameraLgt"]));           
                textBoxLat.Text = dt.Rows[i]["CameraLat"].ToString();
                textBoxLong.Text = dt.Rows[i]["CameraLgt"].ToString();
               
            }

    !the strange thing is that this message is showed before selecting combobox (just after compiling my Winform)

  • Wednesday, April 18, 2012 9:52 AM
     
     

    Hi

    After I appeal the displayCamInfo()in the main form,  i execute the application, the message show 0, then 0, and after i select combobox the 2 first items choised have index 0,  the 3rd selected have 1 .etc

    The position isn't assigned to the right item selected.

    Any idea?

  • Wednesday, April 18, 2012 3:16 PM
     
      Has Code

    The whole concept of using a ComboBox as navigation works well when you are using databinding to other controls, say for example, the other textBoxes you showed in your last post. (You should databind them, BTW). But, I've been testing this particular scenario and it does not work well for grabbing the BindingContext Position while you are in the SelectedIndexChanged event handler, because apparently the Position doesn't change until after. I tried several other events and none of them work for this particular scenario.

    So, I suggest using the SelectedIndex instead of the BindingContext. Your code then becomes

    public void DisplayCamIcon()
    {
      int i = this.comboBox1.SelectedIndex;
      MainMap.Position = new PointLatLng(Convert.ToDouble(dt.Rows[i]["CameraLat"]), Convert.ToDouble(dt.Rows[i]["CameraLgt"]));
      latitude = Convert.ToDouble(dt.Rows[i]["CameraLat"]);
      longitude = Convert.ToDouble(dt.Rows[i]["CameraLgt"]);
    }
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.comboBox1.SelectedIndex > -1)
        {
            DisplayCamIcon();          
        }
    }  

    As for databinding those TextBoxes, take care of that when you fill your DataSet and set the ComboBox1.DataSource. Then you won't have to mess around with setting those TextBox to anything at all in the SelectedIndexChanged event. Simply do this:

      // you're doing this already
      DataTable dt = this.ds.Tables[0];
      comboBox1.DataSource = dt;
      comboBox1.DisplayMember = "CameraName";  
      // so now add these two lines 
      txtBoxLat.DataBindings.Add("Text", dt, "CameraLat");
      txtBoxLong.DataBindings.Add("Text", dt, "CameraLgt")


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Wednesday, April 18, 2012 3:37 PM
     
      Has Code

    UPDATE TO MY LAST POST:

    Right after posting the above, I realized there was another event that could be used, and that is the BindingContext PositionChanged event. Duh!! So, add this to your code, right after the code for setting your combo's DataSource and call DisplayCamIcon() from within this event handler instead of from the SelectedIndexChanged event handler:

    this.BindingContext[dt].PositionChanged += new EventHandler(Form1_PositionChanged);
    private void Form1_PositionChanged(object sender, EventArgs e)
    {
      DisplayCamIcon();
    }


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Wednesday, April 18, 2012 4:25 PM
     
     

    That works very fine, thank you so so much :)

    Another thing, could you please give me some  tuto to learn more SQLite, databinding ...

    Thanks

  • Thursday, April 19, 2012 4:41 AM
     
     

    You're welcome, glad I could help! 

    I don't really have any links bookmarked for Tutorials or anything like that. You're welcome to browse my blog ... I have some decent tips in some of my posts. None of them are tutorials, so it might not be what you're looking for.

    You mentioned databinding, I have a short blog post about that:

    http://geek-goddess-bonnie.blogspot.com/2009/09/keeping-datagrids-and-other-ui-controls.html

    I don't use SQL Lite, I use SQL Server, but I do have a 3-part series on DataAccess that might help you out.

    http://geek-goddess-bonnie.blogspot.com/2009/09/dataaccess-part-i.html
    http://geek-goddess-bonnie.blogspot.com/2009/10/dataaccess-part-ii.html
    http://geek-goddess-bonnie.blogspot.com/2009/10/dataaccess-part-iii.html

    Each post adds extra complexity to the Data Access classes, but more flexiblity. The first post is enough to get you going in the right direction and give you a general idea of the concept, but the second post is more useful. The third post gets into using anonymous delegates and may be too much for a beginner.

    Take a look and see if anything else helps you out ...


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Thursday, May 10, 2012 10:19 AM
     
      Has Code

    Hello;

    I want to delete from dataGidView and update it, I tried this code but nothing happend!

    private void btnDelete_Click(object sender, EventArgs e)
            {
                DataTable dt = ds.Tables[0];
                if (this.dataGridView1.SelectedRows.Count > 0)
                {
                    dt.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
                }
                else
                {
                    MessageBox.Show("Veuillez selectionner une ligne");
                }
            }

    First how could i check in the code if the row is deleted or not?

    For updating, I think that it's possible to edit directly on dataGridView but this, didn't work, miss I someThing?

    Thanks

  • Thursday, May 10, 2012 3:21 PM
     
     

    Don't use .Remove(), use .Delete(). .Remove() physically removes the row from the DataTable leaving no indication that there was ever a row there, whereas .Delete() marks the row as Deleted (in the RowState property) so when you go to update your database, you know which rows have to be deleted.


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Thursday, May 10, 2012 5:03 PM
     
     

    Thank you Bonnie for your reply, but my problem is that code don't work for me! when i click on delete, nothing happens.??

  • Thursday, May 10, 2012 5:10 PM
     
     

    Define "nothing happens".

    Are you not seeing the row getting deleted in the grid? Perhaps you need to add a .Refresh().

    Are you not seeing it getting updated in the database? You don't have the code for it there, I assumed that was elsewhere, perhaps in a Save button.

    You need to be more descriptive about what the problem is. "Nothing happens" tells me nothing.  ;0)   ;0)


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Thursday, May 10, 2012 5:23 PM
     
     
    I'm not seeing the row getting deleted in the grid, and also in database even if I exit the application and i run it again , no thing is deleted.
  • Thursday, May 10, 2012 5:54 PM
     
      Has Code

    This really should have been in a new thread.

    I suspect that you're not seeing anything happen because maybe you're not selecting the whole grid row? Given the code you're using, it won't work otherwise (.SelectedRows means rows, not cells ... checking SelectedCells, you'd use the .RowIndex property).

    Also, you should be deleting from the DefaultView, not the DataTable itself, so the code would be like this instead:

    int index = this.dataGridView1.SelectedCells[0].RowIndex;
    dt.DefaultView[index].Delete();

    And again, you've not shown any DataAccess code ... you've got to have have either TableAdapters or DataAdapters and call their .Update() method (or something similar).


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com


    • Edited by BonnieBMVP Thursday, May 10, 2012 5:55 PM
    •  
  • Thursday, May 10, 2012 6:59 PM
     
     

    I used dataGridView for winform and it propose to enable editing, deleting and adding, I link its datasource directly to myTable coordCamera

    it genereted coordonneeCameraTableAdapter, coordonneeCameraBindingSource and coordCameraDataSet.

    this is the code generated:

    this.coordonneeCameraTableAdapter.Fill(this.coordCameraDataSet.CoordonneeCamera);

    But I don't know how to use DataAdapters?

  • Thursday, May 10, 2012 7:40 PM
     
     

    Did using dt.DefaultView[index].Delete() take care of your first problem? The row should disappear from the grid just fine with that code.

    Next, I suggest that it's time to start a new thread with the TableAdapter/DataAdapter questions. Go to the ADO.NET forum and post your question there: http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataset/threads


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Thursday, May 10, 2012 7:52 PM
     
      Has Code

    I tried dt.DefaultView[index].Delete() but the row didn't disappear!

    this is the code

    private void btnDelete_Click(object sender, EventArgs e)
            {
                DataTable dt = ds.Tables[0];
                if (this.dataGridView1.SelectedRows.Count > 0)
                {
                    //dt.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
    dt.DefaultView[this.dataGridView1.SelectedRows[0].Index].Delete(); //because here i select well the all the row
                }
                else
                {
                    MessageBox.Show("Veuillez selectionner une ligne");
                }
            }
    
    

  • Thursday, May 10, 2012 8:06 PM
     
     

    I suspect that ds.Tables[0] is not the table that is bound to the grid. I have no way of knowing that, but you should be able to look at your grid's DataSource and see what it's bound to. If its DataSource is a BindingSource and not a DataTable, then look at the BindingSource.DataSource and see what it's bound to.

    Somewhere you've got a mismatch between the grid's DataSource and the DataTable you're deleting from.


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Friday, May 11, 2012 1:46 PM
     
      Has Code

    Hi Bonnie;

    You're right, ds.Tables[0] was  not the table that is bound to the grid,  i think this caused when I created in such function new ds.

    Now when I delete a row is disappear from datagrid, but not in the database, when i reload datagrid, it shows me the row deleted!

    private void btnDelete_Click(object sender, EventArgs e)
            {           
                if (this.dataGridView1.SelectedRows.Count > 0)
                {
                    //int index = this.dataGridView1.SelectedRows[0].Index;                
                    //dt.DefaultView[index].Delete();
                    dt.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
                    adapter.Update(ds.Tables["CoordonneeCamera"]);
                    
                }
                else
                {
                    MessageBox.Show("Veuillez selectionner une ligne");
                }
    
                
            }

    When I use the code below it shows me error "The DataAdapter.SelectCommand.Connection property needs to be initialized;"

    private void btnDelete_Click(object sender, EventArgs e)
            {           
                if (this.dataGridView1.SelectedRows.Count > 0)
                {
                    int index = this.dataGridView1.SelectedRows[0].Index;
                    dt.DefaultView[index].Delete();
                    //dt.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
                    adapter.Update(ds.Tables["CoordonneeCamera"]); //the error is here
                    
                }
                else
                {
                    MessageBox.Show("Veuillez selectionner une ligne");
                }
    
                
            }

    this is when i declare adapter:

    SQLiteConnection sqliteconnection1 = new SQLiteConnection(@"data source=coordCamera1.db3"); 
            SQLiteDataAdapter adapter;
            SQLiteCommandBuilder builder;

    { string SQL = "SELECT * FROM CoordonneeCamera"; SQLiteCommand cmd = new SQLiteCommand(SQL); cmd.Connection = sqliteconnection1; sqliteconnection1.Open(); this.adapter = new SQLiteDataAdapter(cmd); this.ds = new DataSet(); this.adapter.Fill(ds, "CoordonneeCamera"); this.builder = new SQLiteCommandBuilder(adapter); try { this.dt = ds.Tables["CoordonneeCamera"]; } catch { } finally { cmd.Dispose(); sqliteconnection1.Close(); }



    • Edited by Ostorlabi Friday, May 11, 2012 2:43 PM
    •  
  • Sunday, May 13, 2012 4:39 AM
     
     

    I'm not sure where you've put that DataAdapter code ... so I can't quite see how it all fits together. What you've posted doesn't look quite right. But, seriously dude, you need to start another thread in the ADO.NET forum with this DataAdapter question, as I mentioned previously. This thread here has drifted far enough ... ;0)

    And, when you show the code snippets in that new thread, please show it a bit more in context. As I said, from what you've already shown, I'm not sure how it all fits together. You can post the link to your new thread in a reply here ... that way if anyone else is following this particular conversation, we'll know where to find the rest of the story.


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Sunday, May 13, 2012 10:47 AM
     
     

    Hi Bonnie;

    thank you again for your response, i've just created new thread for dataAdapter, this is the link:

    http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataset/thread/db906df0-c1c3-4554-ac03-dfe1aca7cf92

    if you see that it is not explicit, please let me know that.

    Also i have onother problem (if you read the post in the link above), when i add onother camera to datagrid and i save it i recall SQL(), to update combobox, but when i choose one element of it it not update the 3 texbox (latitude, longitude and adressIP), this problem is shown just when i update combobox on calling SQL(), I don't know why?

    Any idea?

    Thank you

  • Monday, May 14, 2012 12:06 AM
     
      Has Code

    Yep, I have a pretty good idea what the problem is. Don't recreate your DataSet everytime in your SQL() method. Create the DataSet in the constructor of your Form, then in your SQL() method, simply clear it before filling it:

    ds.Clear();
    adapter.Fill(ds, "CoordonneeCamera");


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Monday, May 14, 2012 6:24 AM
     
     

    thanks, i did what you, it works, but i observed that the combobox is linked with datagridView, when  select one item in the combo is selected also in datagrid and vice versa, is there any proposition to dissociate the two component?

    I still have my problem about delete :)

    • Edited by Ostorlabi Monday, May 14, 2012 6:33 AM
    •  
  • Monday, May 14, 2012 4:01 PM
     
      Has Code

    The problem there is that the Combo and Grid need to be bound to different data sources.

    If you are using BindingSources, you just create different ones to bind your controls to. However, I don't think that you're using BindingSources ... if I recall you are binding directly to the DataTable. I think that in this case, BindingSources are preferable, but I'll show you both.

    First, with BindingSource:

    BindingSource bsCombo = new BindingSource();
    bsCombo.DataSource = ds.Tables["CoordonneeCamera"];
    comboBox1.DataSource = bsCombo;
    comboBox1.DisplayMember = "WhateverItWas";
    BindingSource bsGrid = new BindingSource();
    bsGrid.DataSource = = ds.Tables["CoordonneeCamera"];
    dataGridView1.DataSource = bsGrid;

    Now with DataTables, you need to copy to a new one and use the copy for your Combo DataSource:

    DataTable dtCamera = ds.Tables["CoordoneeCamera"].Copy();
    comboBox1.DataSource = dtCamera;
    comboBox1.DisplayMember = "WhateverItWas";
    dataGridView1.DataSource = ds.Tables["CoordoneeCamera"];


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Tuesday, May 15, 2012 11:27 AM
     
     

    Thank you Bonnie;

    I used the second solution, because I don't know how to use BindingSource to acquire position, rows...

    like here:

    gMapControl1.Position = new PointLatLng(Convert.ToDouble(dtCombo.Rows[i]["CameraLat"]), Convert.ToDouble(dtCombo.Rows[i]["CameraLgt"]));

    thanks again.

  • Tuesday, May 15, 2012 3:25 PM
     
      Has Code

    It's pretty easy with a BindingSource too.

    When you bound directly to a DataTable, you do this to get the position of the row:

    int i = this.BindingContext[dtCombo].Postion;
    string lat = dtCombo.Rows[i]["CameraLat"].ToString();

    With a BindingSource, it's basically the same, because you're still using a .Position property:

    int i = bsCombo.Postion;
    string lat = ds.Tables["CoordonneeCamera"].Rows[i]["CameraLat"].ToString();
    Just keep it in mind for future use. Either methodology is fine ...

    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

  • Wednesday, May 16, 2012 7:22 AM
     
     
    Thank you Bonnie again, really you're a great person :)