提前谢谢你们。我是c#Windows Forms中的新用户。
我有一张id和名称
的表格ID | Name --------------- 1 | Lion 2 | Tiger 3 | Crocodile
如果我想从表格显示到组合框,我确实喜欢这个。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Insert_update_delete_nr2
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(@"CONNECTION_STRING");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
con.Open();
string query = "select * from info";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())//while true
{
comboBox1.Items.Add(dr[0].ToString());//loading values into combo
}
cmd.CommandText = "insert into info3 (name, name_id) values ('"+textBox1.Text+"', '" + comboBox1.Items.Add(dr[0].ToString()) + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
con.Close();
}
private void loadlist()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
con.Open();
cmd.CommandText = "select * from info3";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1]).ToString();
listBox3.Items.Add(dr[3].ToString());
}
}
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// con.Open();
FillDropDownList(string SQL, ComboBox comboBox1);// This giving me error.
// How should I call this FillDropDownlist function? The parameters which are they?
cmd.Connection = con;
listBox3.Visible = false;
loadlist();
}
}
}
它正在尝试插入组合框中显示的名称,而不是id的。
在PHP中它将如下所示:
$sql = " SELECT * FROM info ";
$res = mysql_query($sql);
while ($row = mysql_fetch_array($res)) {
print '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
这将插入id并显示名称。但是我应该怎么做c#? 再次感谢你的时间!
答案 0 :(得分:5)
您可以添加自定义类型,而不是将名称字符串添加到组合框中,而不是:
class Animal
{
public int ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
为每个条目(var animal = new Animal { ID = (int)dr[0], Name = (string)dr[1] };
)创建该类型的对象,将对象添加到组合框中。然后,当您去检索它时,只需将项目转换为Animal类型并获取ID。
var animal = (Animal)comboBox1.SelectedItem;
答案 1 :(得分:3)
如果我理解你的问题,那么你应该按照自己的意愿行事:
使用类似这样的东西加载你的组合框(我现在无法测试,所以我可能会犯一些拼写错误或轻微的语法错误):
* *更新:好的。这是最后一次,当我匆忙时,我试图“在路上”回答一个问题。我的原始代码充满了问题和愚蠢的错别字。真诚的道歉!以下代码包含您尝试执行的所有操作的基本版本。您可能需要根据自己的需要进行调整。
一些建议:
一个。将连接和命令放在using块中,如图所示。
B中。不要在代码中对连接字符串进行硬编码,而是使用Solutions Explorer中的Properties.Settings设计器(左侧)并为连接字符串创建中心引用。然后在所示的代码中引用它。
以下内容执行您尝试实现的基本功能,并在我的计算机上运行:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
this.FillDropDownList();
}
void button1_Click(object sender, EventArgs e)
{
this.SaveComboBoxContent();
}
public void FillDropDownList()
{
string SQL = "SELECT id, name FROM info ORDER BY name";
DataTable dt = new DataTable();
// Set the connection string in the Solutions Explorer/Properties/Settings object (double-click)
using (var cn = new SqlConnection(Properties.Settings.Default.MyConnectionString))
{
using(var cmd = new SqlCommand(SQL, cn))
{
cn.Open();
try
{
dt.Load(cmd.ExecuteReader());
}
catch (SqlException e)
{
// Do some logging or something.
MessageBox.Show("There was an error accessing your data. DETAIL: " + e.ToString());
}
}
}
// UPDATED - The .ValueMember and .DisplayMember properties
// refer to the string name of the field (oops!):
comboBox1.DataSource = dt;
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "name";
}
public void SaveComboBoxContent()
{
string SQL = "INSERT INTO info2 (name_id) VALUES (@name_id)";
using (var cn = new SqlConnection(Properties.Settings.Default.MyConnectionString))
{
using(var cmd = new SqlCommand(SQL, cn))
{
cmd.Parameters.AddWithValue("@name_id", comboBox1.SelectedValue);
cn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
// Do some logging or something.
MessageBox.Show("There was an error accessing your data. DETAIL: " + e.ToString());
}
}
}
}
}
希望有所帮助。