0

приложение winforms. есть combobox куда выведено таблицы из баз данных. я хочу выбирать одну из таблиц баз данных и туда добавлять данные. помогите пожалуйста советами как реализуется. ниже выложил код и изображение.

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

namespace Biling_DSLAM
{
public partial class Openpage : Form
{
    public Openpage()
    {
        InitializeComponent();
    }
 
    
    int id;
    string query;
    DataTable dt = new DataTable("");
    MySqlConnection con = new MySqlConnection("Data Source = 192.168.1.102; Initial Catalog = dslam; UserId = admin; Password = 12345");
    MySqlCommand command;
    private void Openpage_Load(object sender, EventArgs e)

    {

        con.Open();
        var command = new MySql.Data.MySqlClient.MySqlCommand();
        command.Connection = con;
        command.CommandType = CommandType.Text;
        command.CommandText = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'dslam'";

        var adapter = new MySql.Data.MySqlClient.MySqlDataAdapter(command);
        var dataset = new DataSet();
        adapter.Fill(dataset);
        DataTable dt = dataset.Tables[0];
        for (int i = 0; i < dataset.Tables[0].Rows.Count; i++)
        {
            comboBox1.Items.Add(dataset.Tables[0].Rows[i][0].ToString());
        con.Close();
          //  spisok();
    }
    }
    public void spisok()  
    {
        con.Open();

        MySqlDataAdapter adapter = new MySqlDataAdapter(" SELECT* FROM " +comboBox1.Text, con);
        DataSet dset = new DataSet();
        adapter.Fill(dset);
        dataGridView1.DataSource = dset.Tables[0];
        con.Close();
    }
    private void ExecuteQuery(string txtQuery)
    {
        spisok();
        con.Open();
        command = con.CreateCommand();
        command.CommandText = txtQuery;
        command.ExecuteNonQuery();
        con.Close();
    }

    private DataTable AutoNumberedTable(DataTable SourceTable)

    {
        DataTable ResultTable = new DataTable();
        DataColumn AutoNumberColumn = new DataColumn
        {
            ColumnName = "id",
            DataType = typeof(int),
            AutoIncrement = true,
            AutoIncrementSeed = 1,
            AutoIncrementStep = 1
        };
        ResultTable.Columns.Add(AutoNumberColumn);
        ResultTable.Merge(SourceTable);
        return ResultTable;
    }

    private void Addbutton_Click(object sender, EventArgs e)
    {
        try
        {
            if (comboBox1.Text.ToString() == "sats60")

                query = "insert into sta60(id, name, surname, phone, login, dslam, port, date) Values (null, '" + Nametextbox.Text + "', '" + Surnametextbox.Text + "', '" + phonetextbox.Text + "', '" + logintextbox.Text + "', '" + dslamcomboBox.Text + "', '" + porttextbox.Text + "', '" + dateTimePicker1.Text + "')";

            this.dataGridView1.DataSource = AutoNumberedTable(dt);

                if (comboBox1.Text.ToString() == "sats70")
                { 
                    query = "insert into sta70(id, name, surname, phone, login, dslam, port, date) Values (null, '" + Nametextbox.Text + "', '" + Surnametextbox.Text + "', '" + phonetextbox.Text + "', '" + logintextbox.Text + "', '" + dslamcomboBox.Text + "', '" + porttextbox.Text + "', '" + dateTimePicker1.Text + "')";

                }
           if (comboBox1.Text.ToString() == "sta")
            {
                query = "insert into sta(id, name, surname, phone, login, dslam, port, date) Values (null, '" + Nametextbox.Text + "', '" + Surnametextbox.Text + "', '" + phonetextbox.Text + "', '" + logintextbox.Text + "', '" + dslamcomboBox.Text + "', '" + porttextbox.Text + "', '" + dateTimePicker1.Text + "')";

            } 

            MySqlCommand command = new MySqlCommand(query, con);
            
            con.Open();
                if (command.ExecuteNonQuery() == 1)
                {
                    MessageBox.Show("Added!");
                }
                con.Close();

            spisok();
            
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!");
            con.Close();
        }
       
    }

    private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value.ToString());
        Nametextbox.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
        Surnametextbox.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
        phonetextbox.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
        logintextbox.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
        dslamcomboBox.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
        porttextbox.Text = dataGridView1.CurrentRow.Cells[6].Value.ToString();
        dateTimePicker1.Text = dataGridView1.CurrentRow.Cells[7].Value.ToString();
           DataSetDateTime.Local.ToString();
    }

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

    }
    public void fillGrid()
    {

        con.Open();
        MySqlDataAdapter adapter = new MySqlDataAdapter(" SELECT* FROM " + comboBox1.Text, con);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        dataGridView1.DataSource = dt;
        con.Close();

    } 
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
       
        fillGrid();
    }

  }
  }

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

11
  • а в чем конкретно проблема у Вас?
    – Yaroslav
    7 янв 2022 в 11:42
  • Insert into datatable - где datatable хочу вставить значение combobox, куда выведено таблицы баз данных 7 янв 2022 в 11:45
  • не знаю как это реализовать. через условия if (comboBox1.Text.ToString() == "") как-то не получается реализовать 7 янв 2022 в 11:46
  • не вы полняются условия if (comboBox1.Text.ToString() == "")?
    – Yaroslav
    7 янв 2022 в 11:49
  • 1
    1) зачем везде где попало ToString()? вы знаете, что этот метод делает? 2) конкатенация строк в SQL запросе - это вообще последнее дело. Если в двух словах, то используя только интерфейс приложения, я могу удалить вам все данные из базы и вообще что угодно с ней делать. 3) billing
    – aepot
    9 янв 2022 в 13:45

1 ответ 1

0

Нужно сделать так:

if (comboBox1.Text.ToString() == "sats60") 
{
    query = "insert into sta60(id, name, surname, phone, login, dslam, port, date) Values (null, '" + Nametextbox.Text + "', '" + Surnametextbox.Text + "', '" + phonetextbox.Text + "', '" + logintextbox.Text + "', '" + dslamcomboBox.Text + "', '" + porttextbox.Text + "', '" + dateTimePicker1.Text + "')";
    ExecuteQuery(query);
}

Ваш ответ

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

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