C# .NET - how to save checked items of checklistbox in c#.Net

Asked By aman insan on 18-Jun-08 02:16 AM

hi all,

plz if anybody knows how to save the checked items from a checklistbox in c#.net then do tell me soon.i can show the items checked in message box but how can i save that in database.plz tell me clearly.plzzzz

Check this... - Vasanthakumar D replied to aman insan on 18-Jun-08 02:30 AM

Hi,

you can store the checked items in database in two ways...

1. inserting a row for each check item

2. Inserting a commaon row for all items with items are key seperated.

here it the code to insert checked items seperatly,

for (int i = 0; i < checkedListBox1.SelectedItems.Count; i++)

{

        string str = checkedListBox1.SelectedItems[i].ToString();

         //Pass str to your database

}


here is the code to pass the all items together

string str = "";

for (int i = 0; i < checkedListBox1.SelectedItems.Count; i++)

{

if (str == "")

{

str = checkedListBox1.SelectedItems[i].ToString();

}

else

{

str = str + "," + checkedListBox1.SelectedItems[i].ToString();

}

}

//pass str to the database

Here is - Sagar P replied to aman insan on 18-Jun-08 02:40 AM

For that you have to run a loop for selected items of list box; like;

// First check if there are any items checked.
if(checkedListBox1.CheckedItems.Count != 0)
{
   // Then loop through all checked items and insert into db like;
   string str = "";
   for(int cnt = 0; cnt  <= checkedListBox1.CheckedItems.Count - 1 ; cnt ++)
   {
      str =  checkedListBox1.CheckedItems[cnt].ToString();

      SqlConnection myConnection = new SqlConnection("server=(local) \\SQLExpress;Integrated Security=SSPI;database=northwind");

    SqlCommand myCommand = new SqlCommand();
    SqlTransaction myTrans;
   
    // Open the connection.
    myConnection.Open();
   
    // Assign the connection property.
    myCommand.Connection  = myConnection;
   
    // Begin the transaction.
    myTrans = myConnection.BeginTransaction();
   
    // Assign transaction object for a pending local transaction
    myCommand.Transaction = myTrans;
   
    try
    {
      // Insert selected value into database.
      myCommand.CommandText = "Insert into UrTable values(id,'"+str+"')";
      myCommand.ExecuteNonQuery();
            
      myTrans.Commit();
      Console.WriteLine("Record is written to the database!");
    }
    catch(Exception e)
    {
      myTrans.Rollback();
      Console.WriteLine(e.ToString());
      Console.WriteLine("Neither record is written to the database!");
    }
    finally
    {
      myConnection.Close();
    }

   }

}

Try this;

For more info abt the inseration go thr this link;

http://www.codeproject.com/KB/database/simpledbreadwrite.aspx

Also see this;

http://asp.dotnetheaven.com/howto/doc/adoplus/DatabaseTrans.aspx

Best Luck!!!!!!!!!!!!!
Sujit.

You can save it into database table bit column - Deepak Ghule replied to aman insan on 18-Jun-08 02:36 AM

 You can save it into database table bit column

Refer this code to know the selected items in checkedlistbox.

using System;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;

class CheckedListBoxDemo:Form
{
CheckedListBox FavLangs;
GroupBox grpControls;
Button AddValue;
Button EditValue;
Button DeleteValue;
Button ShowValues;
TextBox OldValue;
TextBox NewValue;
Label OldCaption;
Label NewCaption;
CheckBox chkAll;

public CheckedListBoxDemo()
{
grpControls=
new GroupBox();
grpControls.Text="CheckedListBox Demo";
AddValue=
new Button();
AddValue.Text="&Add";
AddValue.Click+=
new EventHandler(Add_Click);
EditValue=
new Button();
EditValue.Text="&Edit";
EditValue.Click+=
new EventHandler(Edit_Click);
DeleteValue=
new Button();
DeleteValue.Text="&Delete";
DeleteValue.Click+=
new EventHandler(Delete_Click);
ShowValues=
new Button();
ShowValues.Text="&Show";
ShowValues.Click+=
new EventHandler(ShowValues_Click);
OldValue=
new TextBox();
OldValue.ReadOnly=
true;
NewValue=
new TextBox();
OldCaption=
new Label();
OldCaption.Text="Old Value:";
NewCaption=
new Label();
NewCaption.Text="New Value:";
chkAll=
new CheckBox();
chkAll.Text="Check/UnCheck All";
chkAll.CheckedChanged+=
new EventHandler(Checked_Changed);
chkAll.Width=175;
OldCaption.Location=
new Point(15,15);
PositionControl(OldCaption,OldValue,
true);
PositionControl(OldCaption,NewCaption,
false);
PositionControl(OldValue,NewValue,
false);
PositionControl(NewCaption,AddValue,
false);
PositionControl(AddValue,EditValue,
true);
PositionControl(EditValue,DeleteValue,
true);
PositionControl(DeleteValue,ShowValues,
true);
PositionControl(AddValue,chkAll,
false);
grpControls.Controls.AddRange(
new Control[]{OldCaption,OldValue,NewCaption,NewValue,AddValue,EditValue,DeleteValue,ShowValues,chkAll});
grpControls.Size=
new Size(450,200);
FavLangs=
new CheckedListBox();
FavLangs.Location=
new Point(10,10);
FavLangs.SelectedIndexChanged+=
new EventHandler(SelectedIndex_Changed);
grpControls.Location=
new Point(FavLangs.Left+FavLangs.Width+20,FavLangs.Top);
this.Controls.AddRange(new Control[]{FavLangs,grpControls});
}

private void PositionControl(Control source,Control destination,bool CanPlaceHorizontal)
{
if(CanPlaceHorizontal)
{
destination.Location=
new Point(source.Left+source.Width+20,source.Top);
}
else
{
destination.Location=
new Point(source.Left,source.Top+source.Height+20);
}
}

private void Add_Click(object sender,EventArgs e)
{
if(NewValue.Text.Trim()!="")
{
FavLangs.Items.Add(NewValue.Text);
}
else
{
MessageBox.Show("Enter a Value to Add");
}
}

private void SelectedIndex_Changed(object sender,EventArgs e)
{
OldValue.Text=FavLangs.Items[FavLangs.SelectedIndex].ToString();
}

private void Edit_Click(object sender,EventArgs e)
{
if(FavLangs.SelectedIndex==-1)
{
MessageBox.Show("Select a Item to Edit");
}
else
{
if(NewValue.Text.Trim()!="")
{
FavLangs.Items[FavLangs.SelectedIndex]=NewValue.Text;
}
else
{
MessageBox.Show("Enter a Value to Edit");
}
}
}

private void Delete_Click(object sender,EventArgs e)
{
if(FavLangs.SelectedIndex!=-1)
{
FavLangs.Items.RemoveAt(FavLangs.SelectedIndex);
}
else
{
MessageBox.Show("Select a Item to Delete");
}
}

private void ShowValues_Click(object sender,EventArgs e)
{
string SelectedValues="The following value(s) are Selected:\n" + new String('-',48) + "\n";
for(int i=0;i<FavLangs.CheckedItems.Count;i++)
{
SelectedValues+=FavLangs.CheckedItems[i].ToString() + "\n";
}
MessageBox.Show(SelectedValues);

//here u can write the code to save checked value into database
}

private void Checked_Changed(object sender,EventArgs e)
{
for(int i=0;i<FavLangs.Items.Count;i++)
{
FavLangs.SetItemChecked(i,chkAll.Checked);
}
}

public static void Main()
{
Application.Run(
new CheckedListBoxDemo());
}
}

m not able to save all checked items - aman insan replied to Vasanthakumar D on 18-Jun-08 03:48 AM

dear sir,

m not able to save allchecked items on just one click.at a time it is able 2 save 1 item.plz help me.

not able 2 save all checked items - aman insan replied to Sagar P on 18-Jun-08 03:52 AM

dear sir,

thanx for ur reply.it do help me.

m not able to save all checked items on just one click.at a time it is able 2 save 1 item.plz help me.

Registry - Aldo Liaks replied to aman insan on 18-Jun-08 04:32 AM

I think you should save to a registry, something like "CURRENT_USER\\Software\\myProductName\\myControlType\\myControlName\\SelectedValues..

Aldo.

try this code.. - Vasanthakumar D replied to aman insan on 18-Jun-08 04:57 AM

Hi,

here is the code ..

string strCon = "your connection string";
SqlConnection sqlCon = new SqlConnection(strCon);
sqlCon.Open();
for (int i = 0; i < checkedListBox1.SelectedItems.Count; i++)

{

        string str = checkedListBox1.SelectedItems[i].ToString();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "insert into yourTableName values('" + str + "')";
        cmd.Connection = sqlCon;
        cmd.ExecuteNonQuery();
}
sqlCon.Close();
still not working - aman insan replied to Vasanthakumar D on 18-Jun-08 05:18 AM

dear sir,

i hav already tried this code but it is able to save only last item checked in list but i want to save all checked items.if u can help then plz.

try this code... - Vasanthakumar D replied to aman insan on 18-Jun-08 05:25 AM

Hi,

try the below code..

string strCon = "your connection string"; SqlConnection sqlCon = new SqlConnection(strCon);
sqlCon.Open();
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)

{

        string str = checkedListBox1.CheckedItems[i].ToString();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "insert into yourTableName values('" + str + "')";
        cmd.Connection = sqlCon;
        cmd.ExecuteNonQuery();
}
sqlCon.Close();

plz chk this - aman insan replied to Vasanthakumar D on 18-Jun-08 05:37 AM

dear sir

don't u think v need to use something like array or arraylist to store all these checked items.i hav tried all earlier ocde sent by u and one another person.

thanx alot

its not requreid... - Vasanthakumar D replied to aman insan on 18-Jun-08 06:02 AM

Hi,

actually what we have used in our code is...

we are looping thoruhg all the checked items in our code. And In each loop we will insert the value to database.

checkboxList1.CheckedItems is collection of checkedlist itmes. It same like array.

so array or arraylist for intermediate storage is not required for this.

u told me registry - aman insan replied to Vasanthakumar D on 18-Jun-08 07:19 AM

dear sir

u told me about something like registring ,how to do tht?

See This - Shailendrasinh Parmar replied to aman insan on 21-Jun-08 08:42 AM
string strName = "";

If (Checkbox1.Checked)
{
     strName  = Checkbox1.Value or Checkbox1.Text;
}

Once you get the value in string, you can insert that value in the database.
lakhan Aanjana replied to Vasanthakumar D on 09-Dec-11 04:21 AM
thanks ....
if we have three cheakedlistbox  for filter  than how to fire select query C#