0

уважаемые люди помогите пожалуйста, есть основная форма с Datagridview данными, Datagrdiview подключен к Mysql.Datagridview извлекает информацию из Mysql, дело в том что на Datagridview помещается мало информации, теперь надо чтобы при нажатии на определенную строку открывалась вторая форма, и эта форма извлекала для этой строки данные из БД mysql, ниже выложил то что сделано, очень прошу помогите! введите сюда описание изображения

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Drawing.Imaging;

namespace LOCAL_PROJECT
{
 public partial class mary : Form
 {
    public mary()
    {
        InitializeComponent();
    }


    //CONNECTION STRING
    DataTable dt = new DataTable("sta");
    MySqlCommand command;
    MySqlConnection con = new MySqlConnection("server = 192.168.1.199; UserId = admin; Password = 12345; database = telecom");
    MySqlDataAdapter adapter = new MySqlDataAdapter();
    int tertip;

    public void spisok()
    {
        con.Open();
        MySqlDataAdapter adapter = new MySqlDataAdapter(" SELECT* FROM `sta` ", con);
        DataSet dset = new DataSet();
        adapter.Fill(dset);
        dataGridView1.DataSource = dset.Tables[0];
        con.Close();
    }

    private void mary_Load(object sender, EventArgs e)
    {
        spisok();
        dataGridView1.EnableHeadersVisualStyles = false;
        dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Lime;
        dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Times new Roman", 13, FontStyle.Bold);
        dataGridView1.ColumnHeadersHeight = 35;
        dataGridView1.DefaultCellStyle.Font = new Font("Times new Roman", 12);
        dataGridView1.Columns[0].Width = 45;
        dataGridView1.Columns[1].Width = 170;
        dataGridView1.Columns[2].Width = 160;
        dataGridView1.Columns[3].Width = 130;
        dataGridView1.Columns[4].Width = 90;
        dataGridView1.Columns[5].Width = 78;
        dataGridView1.Columns[6].Width = 90;
        dataGridView1.Columns[7].Width = 78;
        dataGridView1.Columns[8].Width = 140;
        dataGridView1.Columns[10].Width = 88;
        dataGridView1.Columns[0].HeaderCell.Value = "ID";
        dataGridView1.Columns[1].HeaderCell.Value ="Name";
        dataGridView1.Columns[2].HeaderCell.Value = "satstype";
        dataGridView1.Columns[3].HeaderCell.Value = "prefix";
        dataGridView1.Columns[4].HeaderCell.Value = "size";
        dataGridView1.Columns[5].HeaderCell.Value = "freesize";
        dataGridView1.Columns[6].HeaderCell.Value = "internet_size";
        dataGridView1.Columns[7].HeaderCell.Value = "freeports";
        dataGridView1.Columns[8].HeaderCell.Value = "pots plat";
        dataGridView1.Columns[9].HeaderCell.Value = "internet plat";
        dataGridView1.Columns[10].HeaderCell.Value = "year";
        dataGridView1.Columns[11].HeaderCell.Value = "geolocation C";
        dataGridView1.Columns[12].HeaderCell.Value = "geolocation B";
        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

        //подсказка для Геолокации
        textBox10.Text = "C";
        textBox10.ForeColor = Color.Gray;
        textBox10.TextAlign = HorizontalAlignment.Center;
        Font myfont = new Font("Times new Roman", 14);
        textBox10.Font = myfont;

        //подсказка для Геолокации
        textBox11.Text = "B";
        textBox11.ForeColor = Color.Gray;
        textBox11.TextAlign = HorizontalAlignment.Center;
        Font myfont1 = new Font("Times new Roman", 14);
        textBox11.Font = myfont1;

        
        // SUM 
        textBoxSum.Text = (from DataGridViewRow row in dataGridView1.Rows where row.Cells[4].FormattedValue.ToString() != string.Empty select Convert.ToInt32(row.Cells[4].FormattedValue)).Sum().ToString();
        textBoxSumbosgowrum.Text = (from DataGridViewRow row in dataGridView1.Rows where row.Cells[5].FormattedValue.ToString() != string.Empty select Convert.ToInt32(row.Cells[5].FormattedValue)).Sum().ToString();
        textBoxSumInternet.Text = (from DataGridViewRow row in dataGridView1.Rows where row.Cells[6].FormattedValue.ToString() != string.Empty select Convert.ToInt32(row.Cells[6].FormattedValue)).Sum().ToString();
        textBoxSumDslam.Text = (from DataGridViewRow row in dataGridView1.Rows where row.Cells[7].FormattedValue.ToString() != string.Empty select Convert.ToInt32(row.Cells[7].FormattedValue)).Sum().ToString();
    }

    private void button4_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();
        menu menuu = new menu();
        menuu.Show();
    }

    // Метод автонумерация ID
    private DataTable AutoNumberedTable(DataTable SourceTable)

    {
        DataTable ResultTable = new DataTable();
        DataColumn AutoNumberColumn = new DataColumn();
        AutoNumberColumn.ColumnName = "tb";
        AutoNumberColumn.DataType = typeof(int);
        AutoNumberColumn.AutoIncrement = true;
        AutoNumberColumn.AutoIncrementSeed = 1;
        AutoNumberColumn.AutoIncrementStep = 1;
        ResultTable.Columns.Add(AutoNumberColumn);
        ResultTable.Merge(SourceTable);
        return ResultTable;
    }
      
    private void button5_Click(object sender, EventArgs e)
    {
        con.Open();

        string sql = "insert into sta(tb, name, satstype, prefix, size, freesize, internet_size, freeports, potsplata, internetplata, year, geolocationC, geolocationB) Values (null, '" + textBox2.Text + "', '" + comboBox1.Text + "',  " +
            "'" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "','" + textBox6.Text + "', '" + textBox9.Text + "', '" + textBox8.Text + "', '" + textBox7.Text + "', '" + textBox12.Text + "', '" + textBox10.Text + "', '" + textBox11.Text + "' )";
        this.dataGridView1.DataSource = AutoNumberedTable(dt);
        MySqlCommand cmd = new MySqlCommand(sql, con);
        cmd.ExecuteNonQuery();

        con.Close();
        MessageBox.Show("Added!");
        textBox2.Text = string.Empty;
        comboBox1.Text = string.Empty;
        textBox3.Text = string.Empty;
        textBox4.Text = string.Empty;
        textBox5.Text = string.Empty;
        textBox6.Text = string.Empty;
        textBox7.Text = string.Empty;
        textBox8.Text = string.Empty;
        textBox9.Text = string.Empty;
        textBox10.Text = string.Empty;
        textBox11.Text = string.Empty;
        textBox12.Text = string.Empty;
        spisok();

    }

    // Метод делете
    private void delete(int tb)
    {
        string sql = "DELETE FROM sta WHERE tb=" + tb + "";
        command = new MySqlCommand(sql, con);

        //OPEN CON, EXECUTE DELETE, CLOSE CON

        try
        {
            con.Open();
            adapter = new MySqlDataAdapter(command);
            adapter.DeleteCommand = con.CreateCommand();
            adapter.DeleteCommand.CommandText = sql;

            // PROMT FOR CONFIRMATION

            if (command.ExecuteNonQuery() > 0)
            {
                MessageBox.Show("Deleted!");
            }

            con.Close();

            spisok();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    //Delete button
    private void button3_Click(object sender, EventArgs e)
    {
        string selected = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
        int tb = Convert.ToInt32(selected);
        delete(tb);
    }

   
    private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        try
        {
            tertip = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value.ToString());

            textBox2.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
            comboBox1.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
            textBox3.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
            textBox4.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
            textBox5.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
            textBox6.Text = dataGridView1.CurrentRow.Cells[6].Value.ToString();
            textBox9.Text = dataGridView1.CurrentRow.Cells[7].Value.ToString();
            textBox8.Text = dataGridView1.CurrentRow.Cells[8].Value.ToString();
            textBox7.Text = dataGridView1.CurrentRow.Cells[9].Value.ToString();
            textBox12.Text = dataGridView1.CurrentRow.Cells[10].Value.ToString();
            textBox10.Text = dataGridView1.CurrentRow.Cells[11].Value.ToString();
            textBox11.Text = dataGridView1.CurrentRow.Cells[12].Value.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            con.Close();
        }
    }

    private void textBox13_TextChanged(object sender, EventArgs e)
    {
        con.Open();
        string query = "Select * From sta where name like '%" + textBox13.Text + "%' OR satstype like '%" + textBox13.Text + "%' OR prefix like '%" + textBox13.Text + "%' OR size like '%" + textBox13.Text + "%' OR freesize like '%" + textBox13.Text + "%' OR internet_size like '%" + textBox13.Text + "%' OR freeports like '%" + textBox13.Text + "%' OR potsplata like '%" + textBox13.Text + "%' OR internetplata like '%" + textBox13.Text + "%' OR year like '%" + textBox13.Text + "%' OR geolocationC like '%" + textBox13.Text + "%' OR geolocationC like '%" + textBox13.Text + "%' OR geolocationB like '%" + textBox13.Text + "%'";
        DataSet dset = new DataSet();
        MySqlDataAdapter adapter = new MySqlDataAdapter(query, con);
        MySqlCommandBuilder builder = new MySqlCommandBuilder(adapter);
        adapter.Fill(dset);
        dataGridView1.DataSource = dset.Tables[0];
        con.Close();
    }

    private void button6_Click(object sender, EventArgs e)
    {
        try
        {
            con.Open();
            command = new MySqlCommand("update sta SET name='" + textBox2.Text + "', sa " +
                "tstype='" + comboBox1.Text + "', prefix='" + textBox3.Text + "', size='" + textBox4.Text + "', freesize='" + textBox5.Text + "', internet_size='" + textBox6.Text + "', freeports='" + textBox9.Text + "', potsplata='" + textBox8.Text + "', internetplata='" + textBox7.Text + "', year='" + textBox12.Text + "', geolocationC='" + textBox10.Text + "', geolocationC='" + textBox11.Text + "' WHERE tb='" + tertip + "'", con);
            command.ExecuteNonQuery();
            MessageBox.Show("Updated!");
            con.Close();
            spisok();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

}

2

1 ответ 1

0

UPD: Некоторые переменные в этом коде могут отличаться от тех, что у вас в БД. К примеру в строке string selectedId = dgw1.Rows[dgw.CurrentRow.Index].Cells["Id"].Value.ToString(); обращение свойству Cells["Id"] может вызывать исключение, если в Вашем DGW отсутствует такой столбец. Посмотрите код и исправьте Ваш.

Для начала необходимо получить Id конкретного столбца в DataGridView

Для начала создадим обработчик события в котором получим нужную строку Id

private void dgw1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
   string selectedId = dgw1.Rows[dgw.CurrentRow.Index].Cells["Id"].Value.ToString();
   int selectedDgwId = Convert.ToInt32(selectedId);

   //Делаем запрос в БД и получаем какой-то объект. Есть у вас Id в таблице бд называется как-то по-другому, то измените его в запросе.
   using(SqlCommand cmd = new SqlCommand("SELECT * FROM `mytable` WHERE Id = @id", this.connect))
   {
      DataTable dt = new DataTable();
      cmd.Parameters.AddWithValue("@Id", id);
      SqlDataReader dataReader = cmd.ExecuteReader();
      dt.Load(dataReader);
      dr.Close();
 
      Form2 form2 = new Form2(dt ); //Необходимо, чтобы в конструкторе Вашей формы было свойство нужного Вам класса.
   form2.Show();
   }
}

Чтобы что-то отобразилось на Form2 (форма которая будет открываться по нажатию на dgw) необходимо изменить её конструктор. Ну и допустим что на форме будет какой-нибудь datagridview (допустим с названием form2dgw)

class Form2 : Form
{
   private DataTable _sqlResult;
   public Form2(DataTable sqlResult)
   {
      _sqlResult = sqlResult;
      form2dgw.DataSource = sqlResult;
   }
}
11
  • потерялся, не могли бы вы показать пример в моем коде ? я выложу полностью свой код
    – jun66
    15 окт 2021 в 10:09
  • Выкладывайте. Как выложите - я отредактирую ответ и тегну Вас 15 окт 2021 в 10:18
  • выложил , помогите пожалуйста, критично важная часть проекта, мне нужно чтобы при нажатии на каждую строку открывалась новая окошка и там не важно хоть текстбокс хоть datagrdidview извлекал данные для конкретной строки из БД Mysql
    – jun66
    15 окт 2021 в 10:33
  • Вы умеете в ООП? Если да, то советую Вам создать класс модели, которая будет отражать запись в базе данных. Так же, создать отдельный класс, который будет работать с БД. К примеру в этом классе метод Insert(MyDbClass obj) будет принимать как параметр MyDbClass (он же класс модели), а в SQL запросе у вас будут просто использоваться свойства этого класса 15 окт 2021 в 10:45
  • ООП данный момент очень печально , просто для себя взялся за проект , хочу довести до конца , но понимаю что без ООП никуда
    – jun66
    15 окт 2021 в 10:49

Ваш ответ

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

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