gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:32:58 24 4
gpt4 key购买 nike

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

我有一个包含 id 和 name 的表

ID  | Name---------------1   | Lion2   | Tiger3   | 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com