【问题标题】:c# How to show name and insert values (name's ID ) from combobox in c#c# 如何在 c# 的组合框中显示名称和插入值(名称的 ID)
【发布时间】:2013-01-09 23:24:43
【问题描述】:

提前谢谢你们。我是 c# Windows Forms 的新用户。

我有一个带有 id 和名称的表

身份证 |姓名 --------------- 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#中怎么做? 再次感谢您的宝贵时间!

【问题讨论】:

  • 你有一个 SQL 注入漏洞。
  • 地铁?表格? WPF?银光?视窗电话? ASP.NET?单触?
  • SLaks:抱歉,这是 Windows 窗体

标签: c# winforms combobox


【解决方案1】:

如果我正确理解您的问题,这应该符合您的要求:

用 THIS 之类的东西加载你的组合框(我现在无法测试这个,所以我可能犯了一些拼写错误或轻微的语法错误):

**已更新:好的。那是我最后一次在匆忙中尝试“在旅途中”回答问题。我的原始代码充满了问题和愚蠢的错别字。我真诚的道歉!以下代码包含您尝试执行的所有操作的一个非常基本的版本。您可能需要对其进行调整以满足您的需求。

一些建议:

A.将您的连接和命令放在 using 块中,如图所示。

B.无需在代码中硬编码连接字符串,而是使用解决方案资源管理器中的 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());
                }
            }
        }
    }

}

希望对您有所帮助。

【讨论】:

  • 谢谢 XIVSolions、Itsme 和其他人。今天我病得很重,我明天再试试。
  • 换句话说,您已经提出了四个问题,但只接受了其中一个问题的答案。这告诉人们,当他们花时间回答你的问题时,你不太可能承认他们的努力。当然,您只能接受一个答案。但是这里的游戏化是乐趣和动力的一部分。
  • 我明白了...谢谢 XIVSolutions。我去做。它给了我一些错误你的答案。在公共 void FillDropDownList(string Query, ComboBox DropDownName)
  • 我明白了...谢谢 XIVSolutions。我去做。它给了我一些错误你的答案。在 FillDropDownList(string Query, ComboBox DropDownName) 它在 DropDownName.ValueMember = dt["id"]; 处给了我错误DropDownName.DisplayMember = dt["name"]; .它说不能使用 [] 将索引应用于“system.Data.DataTable”类型的表达式,然后在公共 void SaveComboBoxContent() 上尝试 { cmd.ExecuteNonQuery; // 这里给我一个错误,比如'只有赋值、调用、递增、递减和新对象表达式可以用作语句'
  • 您可以编辑您的帖子并显示您当前的代码吗?哦,顺便说一句,我搞砸了。在我发布的代码中,cmd.ExecuteNonQuery; 应该是 cmd.ExecuteNonQuery()(还记得我在发布代码时无法测试代码的警告吗?) - 请参阅编辑后的代码。
【解决方案2】:

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

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 2016-11-16
    • 2019-08-31
    • 2021-04-06
    • 2016-07-21
    相关资源
    最近更新 更多