多列comboBox但是当选择值时应该是Id
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多列comboBox但是当选择值时应该是Id相关的知识,希望对你有一定的参考价值。
我完成了以下编码,无法使其正常工作..我有一个带有Id,产品,FolderPath的表。我有一个comboBox2,我需要上面的表“Id”和“Product”中的两列数据显示在comboBox2中。现在,如果我从comboBox2中选择一行,我需要将textBox1和textBox2填充为基于comboBox2选择的“Product”和“FolderPath”。就像comboBox2内部显示“Id”和“Product”一样,值必须是“Id”。以下是我的代码;有人可以帮我这个。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Main : Form
{
string connString;
SqlConnection conn;
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
connString = @"Data Source=(LocalDB)MSSQLLocalDB;Initial Catalog=ifz001;";
conn = new SqlConnection(connString);
conn.Open();
Load_Products();
}
void Load_Products()
{
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM FileFolderPath", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox2.Items.Add(dt.Rows[i]["Product"].ToString());
comboBox2.ValueMember = dt.Rows[i]["Id"].ToString();
}
}
catch (Exception lp)
{
MessageBox.Show(lp.Message);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
/*try
{*/
var pix = "SELECT * FROM FileFolderPath WHERE Id = '" + comboBox2.ValueMember + "'";
SqlCommand cmd = new SqlCommand(pix, conn);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
PID.Text = dr["Product"].ToString();
PPath.Text = dr["FolderPath"].ToString();
}
/*}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}*/
}
答案
使用以下代码更改实现:
void Load_Products()
{
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM FileFolderPath", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for(int i = 0; i < dt.Rows.Count; i++)
{
string pid = dt.Rows[i]["Id"].ToString() as string;
string p = dt.Rows[i]["Product"].ToString();
comboBox2.Items.Add(p);
comboBox2.DisplayMember = p;
comboBox2.ValueMember = pid.ToString() as string;
}
}
catch (Exception lp)
{
MessageBox.Show(lp.Message);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
var ppat = "SELECT * FROM FileFolderPath WHERE Id = '" + comboBox2.SelectedIndex + "' ++1";
SqlCommand cmd = new SqlCommand(ppat, conn);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach(DataRow dr in dt.Rows)
{
PID.Text = dr["Id"].ToString();
PPath.Text = dr["FolderPath"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
以上是关于多列comboBox但是当选择值时应该是Id的主要内容,如果未能解决你的问题,请参考以下文章
表单(上)EasyUI Form 表单EasyUI Validatebox 验证框EasyUI Combobox 组合框EasyUI Combo 组合EasyUI Combotree 组合树((代码片