Проблема при отображении результата запроса из базы данных в DataGridView - PullRequest
0 голосов
/ 12 июля 2020

работая с назначением здесь, я могу просматривать все данные из базы данных в представление сетки, но данные выглядят как unsorted, и он отображает все данные, которые я хочу только display the result of a query в DataGridView коде, который у меня есть пробовал:

private void btnmeritbsit_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(dbpath);
    string query = "select Applicant_no,A_Name,Father_Name,T_Matric,O_Matric,M_Percentage,T_Inter ,O_Inter ,I_Percentage from applicantinfo order by I_Percentage desc";
    con.Open();
    dataGridView1.ColumnCount = sdr.FieldCount;
    SqlCommand cmd = new SqlCommand(query, con);
    SqlDataReader sdr = cmd.ExecuteReader();
             
    while (sdr.Read())
    {
        dataGridView1.Rows.Add(sdr["Applicant_no"], sdr["A_Name"], sdr["Father_Name"], sdr["T_Matric"], sdr["O_Matric"], sdr["M_Percentage"], sdr["T_Inter"], sdr["O_Inter"], sdr["I_Percentage"]);
    }
    con.Close();
}

я получал все значения через datatable и dataAdapter, но ничего не работает !! застрял !!

// DataTable dtbl = new DataTable();
// sda.Fill(dtbl);
// dataGridView1.DataSource = dtbl;

Ответы [ 2 ]

1 голос
/ 13 июля 2020

То, что я написал в другом ответе, в картинках. Здесь используется приложение VB, но это не имеет значения, потому что шаги такие же, и вы на самом деле не собираетесь писать больше одной строки кода

enter image description here

Right click project, add new dataset

enter image description here

Right click surface, add tableadapter

enter image description here

Add a connection string, Next. Name it, Next

enter image description here

Add a query that selects all from your table, WHERE (id column) = @id

enter image description here

Rename the methods to add "ByID". It will be obvious why later. Finish:

enter image description here

Right click table adapter, Add Query

enter image description here

Proceed through choosing "Select that returns rows" and entering a query that seeks users by last name:

enter image description here

Give good names to the new methods. Finish. Save:

enter image description here

Go to the forms designer, make sure Data Sources tool panel is showing (View Menu)

enter image description here

Drag the Users grid node from Data Sources onto the form

enter image description here

It has pre-made a textbox for the ID, because that's the first query in the tableadapter. We'll change it to lastname. Click the button, change its name, change the text it shows. Always make sure your control names are up to date and relevant.

enter image description here

You can see I changed the label too, and I also changed the name of the textbox (you can't see it) and I changed the name of everything in the tray under the designer, so it starts with underscore:

enter image description here

I do this because VB is case insensitive and calling variable the same name as their type is a bad idea in any language, and makes intellisense confusing in VB. You don't have to add the leading underscores in C#. It's enough to discriminate on case alone, though arguably not always wise:

enter image description here

Now we need to change the code. Double click the FillBy button. It goes to code. Maybe you have some code already, maybe not. Make sure the code fills the table using the relevant input. This is the only part of the process that really requires you to think about what you're doing and what your variables are called (they may be different to mine)

enter image description here

The code probably defaulted to saying

_usersTableAdapter.FillByID(_myDataSet.Users, new Guid(_lastNameToolStripTextBox.Text));

Because it used to be set up for you to type an id (guid or int, my db has a guid) in that box but we have changed it for lastname. So we need to change the FillByID (and now you see why we give them sensible names, not FillBy1 and FillBy2) so it's FillByLastName, and we need to change the code so we pass a string lastname, not a guid ID

_usersTableAdapter.FillByLastName(_myDataSet.Users, _lastNameToolStripTextBox.Text);

That's the only code you have to write. Remember I named my things on the form using leading underscores, so my code has leading underscores. If you dont rename your things, your code won't have leading underscores

Now run the app:

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

Посмотрите на всех этих Джонов Смитов! Это, конечно, разные пользователи - у каждого свой ID. Вы даже можете написать здесь новые детали и нажать «Сохранить», чтобы обновить базу данных ..

Из одной строчки кода! :)

0 голосов
/ 13 июля 2020

это отлично работает сразу после нескольких изменений :)

private void btnmeritbscs_Click(object sender, EventArgs e)
        {
           
            string dbpath = @"Data Source=DESKTOP-UMA0VFO;Initial Catalog=ApplicationForm;Integrated Security=True";
            SqlConnection con = new SqlConnection(dbpath);
            string query = "select prgstatus,Applicant_no,A_Name,Father_Name,T_Matric,O_Matric,M_Percentage,T_Inter ,O_Inter ,I_Percentage from applicantinfo where prgstatus like 'bscs' order by I_Percentage desc";
            SqlCommand cmd = new SqlCommand(query, con);  
            con.Open();
            SqlDataReader sdr = cmd.ExecuteReader();
            dataGridView1.ColumnCount = sdr.FieldCount;


            while (sdr.Read())
            {
                dataGridView1.Rows.Add(sdr["prgstatus"], sdr["Applicant_no"], sdr["A_Name"], sdr["Father_Name"], sdr["T_Matric"], sdr["O_Matric"], sdr["M_Percentage"], sdr["T_Inter"], sdr["O_Inter"], sdr["I_Percentage"]);
            }
            con.Close();


        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...