Check items registered in the checkedlistbox

Asked

Viewed 1,082 times

1

I am programming in C# in Visual Studio 2015, and I have a form with a checkedListBox with names of several courses (The registration is a student).

When marking and saving, it saves the student’s registration in the student table, and introduces me to my datagridview, where it server for viewing

I need now that when I edit the student registration, the checkedListBox appear checked, in the options that were marked at the time of insertion, but I’m not able to do it, I’m using the datagridview itself to perform the update, that is when I click on the cell of the datagridview it opens me another form to make the registration update, I just can’t get the information of my checkedlistbox.

In short:

I need to pull from the bench and mark the Checkedlistbox options that were marked in the student insertion.

This is my code that plays information from my datagridview to my update form.

private void DG_edit_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        Tela_EditarAluno fmr = new Tela_EditarAluno();

        fmr.TB_cod.Text = DG_edit.CurrentRow.Cells["Cod"].Value.ToString();
        fmr.TB_nome.Text = DG_edit.CurrentRow.Cells["Nome"].Value.ToString();
        fmr.TB_idade.Text = DG_edit.CurrentRow.Cells["Idade"].Value.ToString();
        fmr.TB_endereco.Text = DG_edit.CurrentRow.Cells["Endereço"].Value.ToString();
        fmr.TB_quadra_lote.Text = DG_edit.CurrentRow.Cells["Quadra"].Value.ToString();
        fmr.MD_telefoneFixo.Text = DG_edit.CurrentRow.Cells["Residencial"].Value.ToString();
        fmr.MD_telefoneCel.Text = DG_edit.CurrentRow.Cells["Celular"].Value.ToString();
        fmr.TB_cidade.Text = DG_edit.CurrentRow.Cells["Cidade"].Value.ToString();
        fmr.TB_uf.Text = DG_edit.CurrentRow.Cells["Uf"].Value.ToString();
        fmr.TB_email.Text = DG_edit.CurrentRow.Cells["Email"].Value.ToString();
        fmr.TB_nomepai.Text = DG_edit.CurrentRow.Cells["Pai"].Value.ToString();
        fmr.TB_nomemae.Text = DG_edit.CurrentRow.Cells["Mãe"].Value.ToString();
        fmr.CB_ativo.Text = DG_edit.CurrentRow.Cells["Ativo"].Value.ToString();



        fmr.ShowDialog();
    }

I forgot to mention my checkedlistbox, for this reason I took two prints from the initial registration screen and edit screen. insert image description here

this image is from the editing screen.

inserir a descrição da imagem aqui

This is my home screen to register with my checkedlistbox "ACTIVITIES","NOTE: this column is from my student table" I have an Activities column where he plays my STRINGS that were inserted by the checkedlistbox. and when I click on the cell of datagridview on how in the first edit print it has to check and mark the items that were registered in the registration screen.

inserir a descrição da imagem aqui

  • You said you are not getting popular the listbox with the selected values, where is the routine of recovering the values of BD and popular in the form?

  • Denis good morning. I am using the checkedlistbox, not the listbox, I reformulated my question with the prints, posted the code to take the datagridview information and play in the other form, however I do not know the function to check the items that were registered through the checkedlistbox, and mark them according to what was registered.

1 answer

0


First you need to get the content of the CheckedListBox you need to edit. For ease, I am assuming that you want to get the item from CheckedListBox by its name (label). Use this code:

private int GetItemIndex(string item)
{
    int index = 0;

    foreach (object o in myCheckedListBox.Items)
    {
        if (item == o.ToString())
        {
            return index;
        }

        index++;
    }

    return -1;
}

Get the item index:

var index = GetItemIndex("Nome do Item do checkedBoxList");

Then you take the value of your Datagridview field that will define whether the item will be checked or not.

bool checked = DG_edit.CurrentRow.Cells["Ativo"].Value.ToString() == "Sim"; // Exemplo

So you define whether that item from CheckedListBox that you got content will be checked or not:

myCheckedListBox.SetItemChecked(index, checked);

Do this for every item of your CheckedListBox.

References: Get Checkedlistbox Item by Name

Edit:

You have your object checkedListBox in your form, it contains all the checkboxes.

You have written in the database, or in the case, in your dataGridView whether those check boxes are selected (ticked) or not.

To check every item in your checkedListBox, it is necessary to use the SetItemChecked of CheckedListBox, passing the index of the item you want to check

Example:

// Obter checkBox de Yoga

int indexCbYoga = GetItemIndex("Yoga"); // Utilizando o método GetItemIndex que você vai precisar copiar no seu código, no code behind do seu form

// Pegar o valor da dataGridView que diz se a Yoga está marcada

bool yogaChecked = DG_edit.CurrentRow.Cells["Atividades"].Value.ToString().Contains("Yoga"); // Ou contém "Yoga", não sei como você guarda isto na sua `DataGridView`

// Checar o valor do Yoga no seu `checkedListBox`

myCheckedListBox.SetItemChecked(indexCbYoga, yogaChecked); // Se yogaChecked for true, checa o checkBox Yoga, senão, deixa desmarcado.

Edit 2:

private void DG_edit_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    Tela_EditarAluno fmr = new Tela_EditarAluno();

    fmr.TB_cod.Text = DG_edit.CurrentRow.Cells["Cod"].Value.ToString();
    fmr.TB_nome.Text = DG_edit.CurrentRow.Cells["Nome"].Value.ToString();
    fmr.TB_idade.Text = DG_edit.CurrentRow.Cells["Idade"].Value.ToString();
    fmr.TB_endereco.Text = DG_edit.CurrentRow.Cells["Endereço"].Value.ToString();
    fmr.TB_quadra_lote.Text = DG_edit.CurrentRow.Cells["Quadra"].Value.ToString();
    fmr.MD_telefoneFixo.Text = DG_edit.CurrentRow.Cells["Residencial"].Value.ToString();
    fmr.MD_telefoneCel.Text = DG_edit.CurrentRow.Cells["Celular"].Value.ToString();
    fmr.TB_cidade.Text = DG_edit.CurrentRow.Cells["Cidade"].Value.ToString();
    fmr.TB_uf.Text = DG_edit.CurrentRow.Cells["Uf"].Value.ToString();
    fmr.TB_email.Text = DG_edit.CurrentRow.Cells["Email"].Value.ToString();
    fmr.TB_nomepai.Text = DG_edit.CurrentRow.Cells["Pai"].Value.ToString();
    fmr.TB_nomemae.Text = DG_edit.CurrentRow.Cells["Mãe"].Value.ToString();
    fmr.CB_ativo.Text = DG_edit.CurrentRow.Cells["Ativo"].Value.ToString();

    // Obter checkBox de Yoga

    int indexCbYoga = GetItemIndex(fmr.chekedListBox, "Yoga"); // fmr.chekedListBox é o nome do seu CheckedListBox dentro do seu form. 

    // Pegar o valor da dataGridView que diz se a Yoga está marcada

    bool yogaChecked = DG_edit.CurrentRow.Cells["Atividade"].Value.ToString().Contains("Yoga"); // Ou contém "Yoga", não sei como você guarda isto na sua `DataGridView`

    // Checar o valor do Yoga no seu `checkedListBox`

    fmr.checkedListBox.SetItemChecked(indexCbYoga, yogaChecked); // Se yogaChecked for true, checa o checkBox Yoga, senão, deixa desmarcado.

    // Fazer o mesmo para as outras opções além de Yoga...

    fmr.ShowDialog();

}

private int GetItemIndex(CheckedListBox checkedListBox, string item)
{
    int index = 0;

    foreach (object o in checkedListBox.Items)
    {
        if (item == o.ToString())
        {
            return index;
        }

        index++;
    }

    return -1;
}
  • Murarialex good morning. man I still had doubts, in this solution you posted

  • Good morning, @Lucas_furby, I made an edition with an example, I hope it helps

  • Got it @Murarialex, in this case I don’t need to inform my column name, I would have to reference each string of the checkedlistbox ? and something else I would have to touch my bank to do that insertion because in your code is as "int", my database is as varchar... I am using sql server 2008

  • The int in the case is the Dice Yoga Box inside your checkedListBox in the form, it has nothing to do with the bank. For your checkedListBox object to know that you want to mark or uncheck the Yoga checkbox, you need to pass the Dice from it.

  • I made a small edition, there in the variable yogaChecked put as you can get if the Yoga is marked.

  • I’ll try here @Murarialex, and tell you if it worked.

  • guy I could not deploy this... I put your code within the function of datagridview, it return me error claiming that the activity column was not found, but it is in my bank.

  • Attention in the column name, in my example is "Activities" but in your print is "Activity", so I believe you copied the wrong name, modify the code and revise the names so that they adapt to your code.

  • Dude Voce could add me in skype just to answer some questions [email protected]

  • I’m at work and I don’t have Skype here... I can only help you here.

  • blz, come on... you had asked if my checkedlistbox was selected or tikado.. it is selected, I have a function that makes the insertion of the strings searching in Collections, and add in the activity column... my doubt is I have to put this code that Voce posted inside the datagridview ? and how I’ll call the other form to check

  • this is my function of checkedlist string str = ""; if (Clb_activity.CheckedItems.Count > 0) { for (int i = 0; i < Clb_activity.CheckedItems.Count; i++) { if (str == "") { str = Clb_activity.Checkeditems[i]. Tostring(); } Else { str += "," + Clb_activity.Checkeditems[i]. Tostring(); } }

  • this function is executed in my boot register

  • I made some modifications and put an example of how it would look...

  • I implemented here it worked out the verification, I have to implement in the 8 remaining activities, I have to do this in all 8 remaining ?

  • In theory, yes. There’s a lot of room for improvement there in this code to avoid duplicate code. But it takes time and study and will escape the scope of this question. In the comment "// Fazer o mesmo para as outras opções além de Yoga..." you do the same for the other options.

  • guy worked out, thanks really for the help.

Show 12 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.