c# 如何在 c# 中显示名称并从组合框中插入值(名称的 ID)

标签 c# winforms combobox

先谢谢大家了。我是 c# Windows Forms 的新用户。

我有一个包含 id 和 name 的表

ID  | Name
---------------
1   | Lion
2   | Tiger
3   | Crocodile

If I want to display from a table to combobox I did like this.

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# 中做? 再次感谢您的宝贵时间!

最佳答案

您可以添加自定义类型,而不是将名称字符串添加到组合框:

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;

关于c# 如何在 c# 中显示名称并从组合框中插入值(名称的 ID),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14248303/

相关文章:

c# - 为什么 Resharper 认为 IPrincipal.Identity 永远不会为空?

c# - 日期模式的正则表达式?

c# - 设备唯一 ID 和 Azure 移动服务

c# - 如何获取组合框中的项目数?

c# - 如何抑制 ReSharper 将我的 foreach 循环转换为 LINQ 表达式的建议的单个实例?

winforms - Winforms 中的输入验证

c# - 无法调整已更改图像的大小? C# 窗体

c# - 识别 Web 浏览器的垂直滚动到达 c# 中的最后位置

.net - 是否有用于组合框的内置 .net string/double 对象?

c# - 防止调整大小选择聚焦 ComboBox 中的所有文本