我有一个列名为ITEM的TABLE1,我想在datagridview1的ComboColumn上加载项目。
请告诉我如何加载数据并选择所需的项目名称。 下面是我与数据库的连接字符串。
答案 0 :(得分:0)
这应该让你朝着正确的方向前进。
以下C#程序从数据库中检索值并将其存储在数据集中,然后绑定到组合框。
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Data Source=.;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "select au_id,au_lname from authors";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "au_id";
comboBox1.DisplayMember = "au_lname";
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(comboBox1.Text + " " + comboBox1.SelectedValue);
}
}
}