Гость
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / BindigSource не видит выделенную строку / 1 сообщений из 1, страница 1 из 1
15.01.2017, 13:04
    #39384971
Weroum
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
BindigSource не видит выделенную строку
Взываю к умнейшим! Объясните дураку, что не так делаю? в metroTextBox1 пишу SQL запрос, он мне выводит в dataGridView ответ, но когда я выделяю строку и нажимаю Edit окно не подхватывает значения строки. Я при совершении запроса написал чтобы в BindingSource.DataSource шла this.dataGridView.DataSource, но он все равно говорит мне, что строку я не выделил. Как быть? Помогите пожалуйста. Как заставить эту программу видеть выделенную строку, после того как я ввел запрос в metroTextBox1 ?
Вот мой проект
https://mega.nz/#!NcNglKxK!P5KdaAf2QBIbvteyb73jTSciEw1tpWWHLu3ZKQViDDo
Вот мой код основной формы

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
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)
        {

        }
    }
}



Вот мой код формы для изменения содержимого

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
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;

namespace MetroUI
{
    public partial class frmAddEditStudent : MetroFramework.Forms.MetroForm
    {
        private string obj;
        private Int32Converter obj1;
        private int obj2;
        private DataGridViewCell currentCell;

        public frmAddEditStudent(Student obj)
        {
            InitializeComponent();
            studentBindingSource.DataSource = obj;
            if (chkGender.CheckState == CheckState.Checked)
                chkGender.Text = "Male";
            else if (chkGender.CheckState == CheckState.Unchecked)
                chkGender.Text = "Female";
            else
                chkGender.Text = "???";
        }

        public frmAddEditStudent(string obj)
        {
            this.obj = obj;
        }

        public frmAddEditStudent(Int32Converter obj1)
        {
            this.obj1 = obj1;
        }

        public frmAddEditStudent(int obj2)
        {
            this.obj2 = obj2;
        }

        public frmAddEditStudent()
        {
        }

        public frmAddEditStudent(DataGridViewCell currentCell)
        {
            this.currentCell = currentCell;
        }

        public Student StudentInfo { get { return studentBindingSource.Current as Student; } }
        private void frmAddEditStudent_Load(object sender, EventArgs e)
        {
            // TODO: данная строка кода позволяет загрузить данные в таблицу "dbuiDataSet.Students". При необходимости она может быть перемещена или удалена.
            this.studentsTableAdapter.Fill(this.dbuiDataSet.Students);
            cboCity.DisplayMember = "CityName";
            cboCity.ValueMember = "CityId";
            using (DbEntities db= new DbEntities())
            {
                cboCity.DataSource = db.Cities.ToList();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            studentBindingSource.EndEdit();
            DialogResult = DialogResult.OK;

        }

        private void chkGender_CheckStateChanged(object sender, EventArgs e)
        {
            if (chkGender.CheckState == CheckState.Checked)
                chkGender.Text = "Male";
            else if (chkGender.CheckState == CheckState.Unchecked)
                chkGender.Text = "Female";
            else
                chkGender.Text = "???";
        }
    }
}


...
Рейтинг: 0 / 0
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / BindigSource не видит выделенную строку / 1 сообщений из 1, страница 1 из 1
Целевая тема:
Создать новую тему:
Автор:
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]