【发布时间】:2020-07-16 07:18:46
【问题描述】:
namespace CaseManagementSystem
{
public partial class DataGrid_HBD : UserControl
{
public DataGrid_HBD()
{
InitializeComponent();
// 2 Seconds Timer before connecting to the Database.
// This improves UI rendering on button click
DataGrid_Data();
}
/// <summary>
/// Loading Data Grid
/// </summary>
public void DataGrid_Data()
{
// 2 second delay before loading DataGrid
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };
timer.Start();
timer.Tick += (sender, args) =>
{
timer.Stop();
// Attemption to connect to SQL Server database and populate DataGrid with database tables.
try
{
string connectionString = ("Data Source=WINDOWS-B1AT5HC\\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT [hb_Disputes].[DSP_ID], [hb_disputes].[ACCOUNT], [hb_disputes].[CUST_NAME],[hb_disputes].[PREM_ADDR], [hb_status].[Status], [hb_disputes].[OPENED], [hb_disputes].[DEADLINE], [hb_rpttype].[ReportType], [hb_ratetype].[RateType] FROM [hb_disputes] LEFT JOIN [hb_status] ON [hb_disputes].[STATUS] = [hb_status].[STSID] LEFT JOIN [hb_rpttype] ON [hb_disputes].[RPTTYPE] = [hb_rpttype].[RPTID] LEFT JOIN [hb_ratetype] ON [hb_disputes].[REV_CLS] = [hb_ratetype].[RTID]", connection);
connection.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
connection.Close();
dtGrid.DataContext = dt;
}
catch
{
MessageBox.Show("Database connection is not available at this time. Please contact your database administrator ");
}
};
}
private void dtGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
// User double clicks on DataGrid Row
// Open new Window
// Populate selected textboxes with selected datarow
DataGrid gd = (DataGrid)sender;
DataRowView row_selected = gd.SelectedItem as DataRowView;
var windowToOpen = new Window1();
if(gd !=null )
{
windowToOpen.txt_RowRecrd.Text = row_selected["DSP_ID"].ToString();
windowToOpen.txt_acctnumber.Text = row_selected["ACCOUNT"].ToString();
windowToOpen.txt_custname.Text = row_selected["CUST_NAME"].ToString();
windowToOpen.txt_address.Text = row_selected["PREM_ADDR"].ToString();
windowToOpen.txt_opened.Text = row_selected["OPENED"].ToString();
windowToOpen.txt_deadline.Text = row_selected["DEADLINE"].ToString();
windowToOpen.txt_revcls.Text = row_selected["RateType"].ToString();
windowToOpen.Show();
}
else
{
return;
}
}
目前,当用户双击 Datagrid 行时,我编写了一些代码,仅获取数据表中显示的列并将它们填充到相应的文本框中。
我希望在数据网格上获得有限的信息,并在用户双击文本框和组合框时显示整行数据。
【问题讨论】:
标签: c# sql sql-server wpf datagrid