在我的数据库中,我有一个名为CHIPSET的表,我用它将数据从DB检索到Form1上的CheckedListBox。到现在为止还挺好。 现在,当我将数据插入数据库时,在相应的列下,我得到了" System.Data.DataRowView"选择的已检查项目数量的多少次。我在这里看了一下,我无法弄清楚如何在我的代码中解决这个问题。任何帮助将不胜感激。
这是我的代码:
public partial class Form1 : Form
{
DB db = new DB();
SqlConnection connection;
Chipset catg = new Chipset();
Model model = new Model();
public Form1()
{
InitializeComponent();
loadComboCategory();
}
public void loadComboCategory()
{
checkedListBox1.DataSource = catg.getCategories();
checkedListBox1.DisplayMember = "CHIPSET";
checkedListBox1.ValueMember = "CHIPSET_ID";
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string str = "";
if (checkedListBox1.CheckedItems.Count > 0)
{
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
if (str == "")
{
str = checkedListBox1.CheckedItems[i].ToString();
}
else
{
str += ", " + checkedListBox1.CheckedItems[i].ToString();
}
}
connection = new SqlConnection(@"Data Source=.;Initial Catalog=AOC_DB;Integrated Security=True");
connection.Open();
SqlCommand cmd = new SqlCommand("Insert into data(Item_Id, Items) values(@Item_Id, @Items)", connection);
cmd.Parameters.AddWithValue("@Item_Id", textBox1.Text);
cmd.Parameters.AddWithValue("@Items", str);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted Successfully");
connection.Close();
}
else
{
MessageBox.Show("Please select atleast one item");
}
while (checkedListBox1.CheckedItems.Count > 0)
{
checkedListBox1.SetItemChecked(checkedListBox1.CheckedIndices[0], false);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + e.ToString());
}
if (textBox1.Text != string.Empty)
{
db.openConnection();
model.insertModel(textBox1.Text);
MessageBox.Show("New AOC Model Inserted Successfully", "Insert AOC Model", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Enter The Model Name");
}
}
}
答案 0 :(得分:0)
在搞乱之后,我最终通过替换代码来实现它
str = checkedListBox1.CheckedItems[i].ToString();
有了这个
str = checkedListBox1.GetItemText(checkedListBox1.CheckedItems[i]);
并且还替换了这个
str += ", " + checkedListBox1.CheckedItems[i].ToString();
有了这个:
str += ", " + checkedListBox1.GetItemText(checkedListBox1.CheckedItems[i]);