【发布时间】:2015-08-04 01:48:56
【问题描述】:
我正在用 c# 制作一个 windows 窗体,其中已选中列表框中的所有值都将存储到数据库中。但是代码实际上可以工作:
- 只有最后检查的值会像下面的数据一样重复存储在数据库中
-
famhistory表上的员工 ID (id) 不会显示为外键,但它会像下面的数据一样出现在表name上
表:famhistory
famid famcon id
30 stroke
31 stroke
32 stroke
表:name
eid name
2010-0244 Jam Lagcao
有人可以帮我解决我的问题吗?非常感谢您的帮助。
以下是我在 c# 中的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Npgsql;
namespace WindowsFormsApplication1
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
this.Load += Form6_Load;
button1.Click += button1_Click;
}
private void button1_Click(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlCommand cmd = new NpgsqlCommand("Insert into name(eid, name) Values (@eid, @name)", conn);
cmd.Parameters.AddWithValue("@eid", textBox1.Text);
cmd.Parameters.AddWithValue("@name", textBox2.Text);
conn.Open();
foreach (DataRowView view in checkedListBox1.CheckedItems)
{
NpgsqlCommand cmd2 = new NpgsqlCommand("Insert into famhistory (famcon) Values (@famcon)", conn);
string value = view.Row[0].ToString();
Console.WriteLine(view[checkedListBox1.ValueMember].ToString());
cmd2.Parameters.AddWithValue("@famcon", checkedListBox1.SelectedValue);
cmd2.ExecuteNonQuery();
}
cmd.ExecuteNonQuery();
MessageBox.Show("Data has been saved");
conn.Close();
}
private void Form6_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM condition", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
dt.TableName = "condition";
da.Fill(dt);
checkedListBox1.DataSource = dt;
checkedListBox1.DisplayMember = "conname";
checkedListBox1.ValueMember = "conname";
checkedListBox1.BindingContext = new BindingContext();
string[] condition = dt.Rows[0]["conname"].ToString().Split(',');
}
}
}
【问题讨论】:
-
你创建了一个值变量并且从不使用它。
-
@dbugger 抱歉,我不明白你的意思
-
这可能是您要保存到数据库的内容... string value = view.Row[0].ToString();但你永远不会用它做任何事情。
-
是的。但我不知道如何实际使用它。能给个主意吗?
标签: c# npgsql checkedlistbox