Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > .NET Frameworks (точка нет фреймворки) > C# (си шарп)
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 15.01.2017, 13:12   #1
Weroum
Новичок
Джуниор
 
Регистрация: 14.01.2017
Сообщений: 1
Печаль BindigSource не видит выделенную строку

Взываю к умнейшим! Объясните дураку, что не так делаю? в metroTextBox1 пишу SQL запрос, он мне выводит в dataGridView ответ, но когда я выделяю строку и нажимаю Edit окно не подхватывает значения строки. Я при совершении запроса написал чтобы в BindingSource.DataSource шла this.dataGridView.DataSource, но он все равно говорит мне, что строку я не выделил. Как быть? Помогите пожалуйста. Как заставить эту программу видеть выделенную строку, после того как я ввел запрос в metroTextBox1 ?
Вот мой проект
https://mega.nz/#!NcNglKxK!P5KdaAf2Q...WWHLu3ZKQViDDo
Код:
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 System.Data.SqlClient;


namespace MetroUI
{
    public partial class Form1 : MetroFramework.Forms.MetroForm
    {
        public Form1()
        {
            InitializeComponent();
            

        }
        int ABZ, AZZZ;

        private async void mtAdd_Click(object sender, EventArgs e)
        {
            using (frmAddEditStudent frm = new frmAddEditStudent(new Student() { Gender = false }))
            {
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        studentsBindingSource.Add(frm.StudentInfo);
                        db.Students.Add(frm.StudentInfo);
                        await db.SaveChangesAsync();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            this.studentsTableAdapter.Fill(this.dbuiDataSet.Students);


        }

        private void mtRefresh_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            studentsBindingSource.DataSource = db.Students.ToList();
            cityBindingSource.DataSource = db.Cities.ToList();
            Cursor.Current = Cursors.Default;
        }
        DbEntities db;
       

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: данная строка кода позволяет загрузить данные в таблицу "dbuiDataSet.Students". При необходимости она может быть перемещена или удалена.
            this.studentsTableAdapter.Fill(this.dbuiDataSet.Students);


            

        }

        private async void mtEdit_Click(object sender, EventArgs e)
        {
            
            if (ABZ == 1)
            {
               

                Student StudentId = studentsBindingSource.Current as Student;
                if (StudentId != null)

                {
                    using (frmAddEditStudent frm = new frmAddEditStudent(StudentId))
                    {
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            try
                            {
                                studentsBindingSource.EndEdit();
                                await db.SaveChangesAsync();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }



                this.studentsTableAdapter.Fill(this.dbuiDataSet.Students);
            }
            else {

                db = new DbEntities();
                studentBindingSource.DataSource = db.Students.ToList();
                Student StudentId = studentBindingSource.Current as Student;
                if (StudentId != null)

                {
                    using (frmAddEditStudent frm = new frmAddEditStudent(StudentId))
                    {
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            try
                            {
                                studentsBindingSource.EndEdit();
                                await db.SaveChangesAsync();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }



                this.studentsTableAdapter.Fill(this.dbuiDataSet.Students);
            }

        }

        private void mtDelete_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Do you want to delete?", ProductName, MessageBoxButtons.YesNo,
               MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                foreach (DataGridViewRow Rows in dataGridView.SelectedRows)
                {
                    
                    // это выбранная строка тоже самое что CurrentRow оба возвращают DataGridViewRow
                    int index = Rows.Index; // индекс выбранной строки
                    dataGridView.Rows.RemoveAt(index);
                    this.studentsTableAdapter.Update(this.dbuiDataSet);
                }

            }
        }

        private async void mtSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Do you want to save the changes?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    studentsBindingSource.EndEdit();
                    await db.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void metroTextBox1_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-UL5AJO7;Initial Catalog=dbui;Integrated Security=True");
            con.Open();
            SqlDataReader reader = null;
            if (this.dataGridView.Visible == true)
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText = "Select * from Students WHERE FullName LIKE '" + metroTextBox1.Text + "%'";
                var table = new DataTable();
                table.Load(cmd.ExecuteReader());
                this.dataGridView.DataSource = table;
                
                ABZ = 1;
                con.Close();
                con.Dispose();
                
            }
           
            if (ABZ==1)
            {
                studentsBindingSource.DataSource = this.dataGridView.DataSource;
            }
            }
           


    private void studentsBindingSource_CurrentChanged(object sender, EventArgs e)
        {

        }
    }
}
Weroum вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
как добавит текста в edit3 выделенную строку на stringgrid ? alman12 Общие вопросы Delphi 11 01.06.2014 01:30
Спарсить то что видит снифер, но не видит браузер... FleXik Общие вопросы Delphi 8 11.12.2012 00:44
DBGridEh: запомнить выделенную строку при обновлении new player Компоненты Delphi 5 09.04.2011 10:18
Добавлений примечания в выделенную ячейку bud-dy Microsoft Office Excel 2 11.02.2010 16:16
ListBox ----- выполнить выделенную строку! Disday Общие вопросы Delphi 13 05.11.2008 20:37