c#如何显示名称并从c#的组合框中插入值(名称的ID) [英] c# How to show name and insert values (name's ID ) from combobox in c#

查看:58
本文介绍了c#如何显示名称并从c#的组合框中插入值(名称的ID)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先谢谢大家.我是c#Windows窗体的新用户.

Thank you guys in advance. I'am new user in c# Windows Forms.

我有一张ID和名字都在的桌子

I have a table with id's and 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.


And it's trying inserting what is showing in combobox which it's name, not id's.

在PHP中将如下所示:

in PHP it would be like the following:

$sql =  " SELECT * FROM info ";
$res = mysql_query($sql);
while ($row = mysql_fetch_array($res)) {
    print '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}

这将插入id并显示名称.但是我应该如何在C#中做呢?再次感谢您的宝贵时间!

That would insert id's and showing names. But How should I do in c#? Thank you again for your time!

推荐答案

如果我正确理解了您的问题,这应该可以满足您的要求:

If I understand your question correctly, this should do what you are seeking:

在组合框中加载类似THIS(我现在无法对此进行测试,因此我可能犯了一些错字或较小的语法错误):

Load your combo box with something like THIS (I can't test this right now, so I may have made some typo's or minor syntax errors):

* *更新:好的.那是我最后一次在匆忙中尝试在旅途中"回答问题的最后一次.我原来的代码到处都是问题和愚蠢的错字.诚挚的歉意!以下代码包含了您要执行的所有操作的非常基本的版本.您可能需要对其进行调整以适合您的需求.

**UPDATED: Ok. That is the LAST time I try to answer a question "on the go" when I'm in a rush. My original code was rife with issues and stupid typos. My sincere apologies! The following code includes a very basic version of everything you are trying to do. You may need to adapt it to suit your needs.

一些建议:

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

A. Place your connection and command in the using blocks, as shown.

B.可以使用解决方案资源管理器(位于左侧)中的Properties.Settings设计器,并为连接字符串创建中央引用,而不是在代码中对连接字符串进行硬编码.然后在所示的代码中引用它.

B. Instead of hard-coding your connection string in your code, use the Properties.Settings designer in the Solutions Explorer (off to the left) and create a central reference for your connection string. Then reference it in code like shown.

以下代码执行您要实现的基本功能,并在我的计算机上运行:

The following performs the basic functionality you are trying to achieve, and runs on my machine:

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());
                }
            }
        }
    }

}

希望有帮助.

这篇关于c#如何显示名称并从c#的组合框中插入值(名称的ID)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆