0

Есть колонка Online, которая создается путем запроса со значениями: 1 - если онлайн и 0 - если оффлайн. Я создал дополнительную колонку с иконками. Как мне подставить вместо значений 1 и 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 BTA_USERS 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 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);
        SqlDataAdapter usersDataAdapter = new SqlDataAdapter(strUsersData, connection);
        usersDataAdapter.Fill(data, "BTA_USERS");

        // Add data from the sta_Messages 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 BTA_USERS 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;

        usersDataGridView.Columns[0].Visible = false;

        Image i = new Bitmap(@"D:\greenround.ico");
        Image i2 = new Bitmap(@"D:\redround.ico");              

        for (int n = 0; n < usersDataGridView.RowCount; n++)
        {
            if (Convert.ToChar(usersDataGridView.Rows[n].Cells[2].Value) == '1')
            {
                usersDataGridView.Rows[n].Cells[2].Value = i;
            }
            else if (Convert.ToChar(usersDataGridView.Rows[n].Cells[2].Value) == '0')
            {
                usersDataGridView.Rows[n].Cells[2].Value = i2;
            }
        }
    }
    catch (SqlException)
    {
        MessageBox.Show("Помилка!");
    }
}

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

1
  • @AlexanderPetrov понял, исправил
    – eugenes
    7 ноя 2019 в 11:51

2 ответа 2

1

Способы есть разные.

Например, можно добавить колонку нужного типа: Icon или Image. Пройдясь циклом по таблице, задать значения ячейкам этой колонки. После чего ненужную колонку удаляем или скрываем, в зависимости от того, нужна ли она где-то далее по логике действий.

Приведение выполняйте к тому типу, который у вас используется.

var usersTable = data.Tables["BTA_USERS"];
var statusColumn = usersTable.Columns.Add("Status", typeof(Icon)); // or Image

foreach (DataRow row in usersTable.Rows)
{
    if ((int)row["Online"] == 0) // or (string)
        row["Status"] = i;
    else
        row["Status"] = i2;
}

//usersTable.Columns["Online"].ColumnMapping = MappingType.Hidden;
usersTable.Columns.Remove("Online");
0

Вам нужно получить Image, а после в зависимости от условия выбора вставить его как value ячейки.

Image image1= new Bitmap("C:\\Users\\Pictures\\img1.jpg");
Image image2= new Bitmap("C:\\Users\\Pictures\\img2.jpg");
if(/*условие выбора*/)
{
    dataGridView1.Rows[i].Cells[j].Value = image1;
}
else
{
    dataGridView1.Rows[i].Cells[j].Value = image2;
}

Примерно как-то так...

6
  • в условии если dataGridView1.Rows[i].Cells[j].Value == '1' то image1, если '0' то image2, так я понимаю? и строки с ячейками в цикле получаем?
    – eugenes
    7 ноя 2019 в 11:18
  • В условии то, как Вы определяете какая картинка должна быть показана. Как Вы это определяете решать Вам. Вообще вместо того чтобы ориентироваться на колонку грида гораздо лучше сделать класс модели и опираться на её свойства, но это моё ИМХО.
    – Streletz
    7 ноя 2019 в 11:28
  • вроде получилось (отредактировал главный вопрос), но саму иконку не выводит, скриншот приложил
    – eugenes
    7 ноя 2019 в 11:38
  • Говорят помогает переключение виртуального режима.
    – Streletz
    7 ноя 2019 в 11:47
  • смена режима не помогла
    – eugenes
    7 ноя 2019 в 11:52

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

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