提前谢谢你们。我是 c# Windows Forms 的新用户。
我有一个带有 id 和 name 的表
身份证 | 姓名 --------------- 1 | 狮子 2 | 老虎 3 | 鳄鱼
如果我想从表格显示到组合框,我确实喜欢这样。
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#中怎么做?再次感谢您的宝贵时间!