Create a project in Visual Studio and add DataGridView to the Form.
Add the following code to the Form1.cs class.
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;
namespace ComboBoxInDataGridView
{
public partial class Form1 : Form
{
DataGridViewComboBoxColumn column;
public Form1()
{
InitializeComponent();
dropDownCell();
fillSalesRepsInsideTable();
}
private void dropDownCell() {
column = new DataGridViewComboBoxColumn();
dataGridView1.Columns.Add(column);
column.DisplayMember = "Guide";
column.ValueMember = "10";
column.HeaderText = "Sales Rep.";
//column.ToolTipText = "Please enter the name of the Sales Rep.";
//column.Name = "nbb";
column.FlatStyle = FlatStyle.Flat;
// column.DataPropertyName = "sales rep";
}
private void fillSalesRepsInsideTable()
{
string connectionString = "Server=localhost\\sqlexpress;Database=test;User Id=sa;Password=abc123;";
SqlConnection connection = new SqlConnection(connectionString);
String query = @"Select * From student;";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader sqlReader = command.ExecuteReader();
try
{
while (sqlReader.Read())
{
column.Items.Add(sqlReader[1]);
}
}
catch (Exception ex)
{
MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
sqlReader.Close();
}
connection.Close();
}
}
}
See the result by running the project.
Do not forget to leave your comments below.
No comments:
Post a Comment