0

Есть метод для связи между таблицами и биндинг к гриду

private void GetData()
{
    try
    {
        var loadData = cs.LoadFile("DataConnection.xml");
        string connString = String.Format("Data Source={0};Initial Catalog={1};User Id={2};Password={3}", loadData.Host, loadData.Database, loadData.UserId, loadData.PWD);
        SqlConnection connection = new SqlConnection(connString);

        // Create a DataSet.
        DataSet data = new DataSet();
        data.Locale = System.Globalization.CultureInfo.InvariantCulture;

        // Add data from the Customers table to the DataSet.
        //string strUsersData = String.Format("select * from BTA_USERS where \"ID\" != {0} and \"isDelUser\" is null", loadData.LastId);
        string strUsersData = String.Format("select \"NAME\", case when BTA_USERS_ENTEREXIT.\"id\" is not null then '1' else '0' end as Online from BTA_USERS " +
            "left join BTA_USERS_ENTEREXIT on BTA_USERS.\"ID\" = BTA_USERS_ENTEREXIT.\"user_id\" " +
            "and cast(convert(char(8), BTA_USERS_ENTEREXIT.\"date_enter\", 112) as datetime) = cast(convert(char(8), GETDATE(), 112) as datetime) " +
            "and BTA_USERS_ENTEREXIT.\"date_exit\" = null " +
            "where BTA_USERS.\"ID\" != {0} and BTA_USERS.\"isDelUser\" is null " +
            "order by Online asc, \"NAME\" asc", loadData.LastId);
        SqlDataAdapter usersDataAdapter = new SqlDataAdapter(strUsersData, connection);
        usersDataAdapter.Fill(data, "BTA_USERS");

        // Add data from the Orders table to the DataSet.
        string strPostData = String.Format("select \"GetText\", case when \"SetUser_id\" = {0} then \"GetUser_id\" else \"SetUser_id\" end as Sender, case when \"SetUser_id\" = {0} then 'outgoing' else 'incoming' end as Stream from sta_Messages where \"SetUser_id\" = {0} or \"GetUser_id\" = {0}", loadData.LastId);
        SqlDataAdapter postsDataAdapter = new SqlDataAdapter(strPostData, connection);
        postsDataAdapter.Fill(data, "sta_Messages");

        //// Establish a relationship between the two tables.
        DataRelation relation = new DataRelation("UsersMessages",
            data.Tables["BTA_USERS"].Columns["ID"],
            data.Tables["sta_Messages"].Columns["Sender"]);
        data.Relations.Add(relation);

        // Bind the master data connector to the Customers table.
        BindingSource usersBindingSource = new BindingSource();
        BindingSource postsBindingSource = new BindingSource();
        usersBindingSource.DataSource = data;
        usersBindingSource.DataMember = "BTA_USERS";

        postsBindingSource.DataSource = usersBindingSource;
        postsBindingSource.DataMember = "UsersMessages";

        usersDataGridView.DataSource = usersBindingSource;
        postsDataGridView.DataSource = postsBindingSource;
    }
    catch (SqlException)
    {
        MessageBox.Show("Помилка!");
    }
}

Изначально метод был написан для вывода юзеров и истории сообщений между ними. (первый заремленый strUsersData), после переделал запрос для того, чтобы отображало кто в данный момент онлайн (через 3ю таблицу с данными о входе\выходе юзера с системы) и теперь выдает исключение

введите сюда описание изображения

Я понимаю, что одна с колонок возвращает null, но не пойму почему. Буду благодарен за подсказку.

2
  • вроде разобрался, в select'e я не вытягивал поле ID и в привязке возвращало null и нечему было привязываться
    – eugenes
    7 ноя 2019 в 10:01
  • 1
    Можете сами опубликовать вопрос и принять его (вам будет плюс в репутацию). 7 ноя 2019 в 12:15

1 ответ 1

1

В select'e добавил выборку по полю ID, тем самым стало к чему привязываться между таблицами, где возвращало null

string strUsersData = String.Format("select BTA_USERS.\"ID\", \"NAME\", case when BTA_USERS_ENTEREXIT.\"id\" is not null then '1' else '0' end as Online from BTA_USERS " +
                "left join BTA_USERS_ENTEREXIT on BTA_USERS.\"ID\" = BTA_USERS_ENTEREXIT.\"user_id\" " +
                "and cast(convert(char(8), BTA_USERS_ENTEREXIT.\"date_enter\", 112) as datetime) = cast(convert(char(8), GETDATE(), 112) as datetime) " +
                "and BTA_USERS_ENTEREXIT.\"date_exit\" = null " +
                "where BTA_USERS.\"ID\" != {0} and BTA_USERS.\"isDelUser\" is null " +
                "order by Online asc, \"NAME\" asc", loadData.LastId);

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.