我已经完成了以下编码,无法使其正常工作。 我有一个带有ID,产品,FolderPath的表。 我有一个comboBox2,在这里我需要上表“ Id”和“ Product”中的两列数据显示在comboBox2中。现在,如果我从comboBox2选择行,则需要根据comboBox2选择,将textBox1和textBox2填充为“ 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);
}*/
}
答案 0 :(得分:0)
使用以下代码更改可实现:
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);
}
}