【问题标题】:Appcrash after try to insert a datagrid尝试插入数据网格后 Appcrash
【发布时间】:2021-07-30 17:57:28
【问题描述】:

尝试使用 sqlcommand 创建 DataGrid 后,应用程序崩溃。我已经阅读了很多代码来获得数据网格的成功,但没有办法:/

有人可以帮助我吗?

using System;using System.Windows;using System.Windows.Controls;using Microsoft.Data.SqlClient;

命名空间 SUS { 公共部分类 MainWindow : 窗口 { SqlConnection Cnx = new SqlConnection(); SqlCommand Cmd = new SqlCommand(); SqlDataReader 博士;

    public MainWindow()
    {
        InitializeComponent();
        Title = "Stop User Sage";
        
        refresh.IsEnabled = false;

        if (txtServerName.Text == "")
        {
            txtServerName.Text = string.Concat(Environment.MachineName, @"\SAGE_ERP");
        }
    }

    private void txtServerName_Initialized(object sender, EventArgs e)
    {
        txtServerName.Text = Properties.Settings.Default.sa_ServerName;
    }

    private void txtServerName_SelectionChanged(object sender, RoutedEventArgs e)
    {
        Properties.Settings.Default.sa_ServerName = txtServerName.Text;
        Properties.Settings.Default.Save();
    }

    private void cmbAuthentification_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (!cmbAuthentification.IsLoaded)
        {
            cmbAuthentification.Loaded += (ss, ee) => cmbAuthentification_SelectionChanged(sender, e);
            return;
        }

        if (cmbAuthentification.SelectedIndex == 0)
        {
            txtUserID.IsEnabled = false;
            txtUserID.Clear();
            txtUserPwd.IsEnabled = false;
            txtUserPwd.Clear();
        }

        if (cmbAuthentification.SelectedIndex == 1)
        {
            txtUserID.IsEnabled = true;
            txtUserPwd.IsEnabled = true;
        }
    }

    private void cmbDatabase_DropDownOpened(object sender, EventArgs e)
    {

        cmbDatabase.Items.Clear();

        try
        {
            if (Cnx.State == System.Data.ConnectionState.Open)
            {
                Cnx.Close();
            }
            if (cmbAuthentification.Text.Equals("Windows"))
            {
                SQL_Connection.ConnectionString = @"Server = " + txtServerName.Text + "; Integrated Security = SSPI;";
                Cnx.ConnectionString = SQL_Connection.ConnectionString;
            }
            else if (cmbAuthentification.Text.Equals("SQL Server"))
            {
                SQL_Connection.ConnectionString = @"Server = " + txtServerName.Text + "; User ID =" + txtUserID.Text + "; Password=" + txtUserPwd.Text + ";";
                Cnx.ConnectionString = SQL_Connection.ConnectionString;
            }
            Cnx.Open();
            Cmd.Connection = Cnx;
            Cmd.CommandText = "SELECT [name] AS [database],database_id FROM sys.databases WHERE case WHEN state_desc = 'ONLINE' THEN object_id(quotename([name]) +'.[dbo].[P_DOSSIER]', 'U') END IS NOT NULL ORDER BY 1;";
            dr = Cmd.ExecuteReader();
            while (dr.Read())
            {
                cmbDatabase.Items.Add(dr["Database"].ToString());
            }
            Cnx.Close();
        }
        catch (Exception exception_connection)
        {
            MessageBox.Show(exception_connection.Message, "OOoopssss !!!", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void cmbDatabase_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (cmbDatabase.SelectedItem == null)
        {
            refresh.IsEnabled = false;
            return;
        }
        else refresh.IsEnabled = true;
    }

    private void refresh_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (Cnx.State == System.Data.ConnectionState.Open)
            {
                Cnx.Close();
            }
            if (cmbAuthentification.Text.Equals("Windows"))
            {
                SQL_Connection.ConnectionString = @"Server = " + txtServerName.Text + "; Integrated Security = SSPI;";
                Cnx.ConnectionString = SQL_Connection.ConnectionString;
            }
            else if (cmbAuthentification.Text.Equals("SQL Server"))
            {
                SQL_Connection.ConnectionString = @"Server = " + txtServerName.Text + "; User ID =" + txtUserID.Text + "; Password=" + txtUserPwd.Text + ";";
                Cnx.ConnectionString = SQL_Connection.ConnectionString;
            }
            Cnx.Open();
            Cmd.Connection = Cnx;
            Cmd.CommandText = ("USE " +cmbDatabase.Text+ ";SELECT a.cbSession AS [UID_ID_Session],b.nt_username AS [UID_UserName],b.hostname AS [UID_ComputerName] FROM cbUserSession a INNER JOIN master..sysprocesses b ON a.cbSession = b.spid;");
            dr = Cmd.ExecuteReader();
            while (dr.Read())
            {
                dgConnected_Users.ItemsSource = dr;

            }
            Cnx.Close();
        }
        catch (Exception exception)
        {
            MessageBox.Show("Erreur de chargement des données pour le motif suivant : \n" + exception.Message, "OOoopssss !!!", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }
}

}

【问题讨论】:

  • 你能提供堆栈跟踪和错误信息吗?

标签: c# wpf datagrid


【解决方案1】:

我认为您的问题在于您如何处理从数据读取器返回的数据。这段代码就在这里:

Cmd.CommandText = "SELECT [name] AS [database],database_id FROM sys.databases WHERE case WHEN state_desc = 'ONLINE' THEN object_id(quotename([name]) +'.[dbo].[P_DOSSIER]', 'U') END IS NOT NULL ORDER BY 1;";
dr = Cmd.ExecuteReader();
while (dr.Read())
{
   cmbDatabase.Items.Add(dr["Database"].ToString());
}

用 if 语句包装 while 语句以防止出现空结果集并更改您使用读取器的方式,如下所示:

    if (reader.HasRows)
    {
        while (reader.Read())
        {
             cmbDatabase.Items.Add(reader.GetString(0));
        }
    }

【讨论】:

  • 不不,那部分没问题。我改变了这部分:` dr = Cmd.ExecuteReader(); while (dr.Read()) { dgConnected_Users.ItemsSource = dr; }` 使用:SqlDataAdapter da = new SqlDataAdapter(Cmd); DataTable dt = new DataTable("Connected_Users"); da.填充(dt); dgConnected_Users.ItemsSource = dt.DefaultView;
猜你喜欢
  • 2020-07-29
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 2016-08-18
相关资源
最近更新 更多