简体   繁体   English

C# 中的 Datagridview 没有从 SQL Server 数据库中检索所有记录

[英]Datagridview in C# is not retrieving all the records from SQL server database

I have a visual studio project for our student records and the records are coming from our online registration app.我有一个用于学生记录的视觉工作室项目,这些记录来自我们的在线注册应用程序。 Then the database saves it.然后数据库保存它。 But the problem is my datagridview is not retrieving all the records from the database when I'm trying to retrive it using my other app.但问题是当我尝试使用我的其他应用程序检索它时,我的 datagridview 没有从数据库中检索所有记录。 In other words our online app gathers data online and the other app is used to displays it for processing.换句话说,我们的在线应用程序在线收集数据,而另一个应用程序用于显示数据以进行处理。

private void DisplayOnlineApplications(List<StudentInformationOnlineModel> Applicants)
{
    dataGridView1.Rows.Clear();

    foreach (var applicant in Applicants)
    {
        string gender = applicant.Gender.Substring(0, 1);
        dataGridView1.Rows.Add(applicant.ApplicationID, applicant.StudentStatus, applicant.LRN, applicant.StudentName, gender, applicant.EmailAddress, applicant.MobileNo, applicant.EducationLevel, applicant.CourseStrand, applicant.YearLevel, applicant.ApplicationDate.ToString("MM-dd-yyyy hh:mm tt"));
        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Tag = applicant;
    }
}

Your code needs some improvements.您的代码需要一些改进。 You don't need to manually add rows.您不需要手动添加行。 Simply do.干脆做。

private void DisplayOnlineApplications(List<StudentInformationOnlineModel> Applicants)
{
    dataGridView1.DataSource = Applicants;
}

For Gender field you can handle DataGridView.CellFormatting event对于Gender字段,您可以处理DataGridView.CellFormatting事件

private void DataGridView1_CellFormatting(
    object sender, DataGridViewCellFormattingEventArgs e)
{
    var dataPropertyName = dataGridView1.Columns[e.ColumnIndex].DataPropertyName;
    if (dataPropertyName == nameof(StudentInformationOnlineModel.Gender))
    {
        e.Value = (e.Value as string).Substring(0, 1);
    }
}

If you need to get your object in row then you can do (at index 0 for example)如果您需要将对象排成一行,那么您可以这样做(例如在索引0处)

var item = dataGridView1.Rows[0].DataBoundItem;
var studentInformationOnlineModel = item as StudentInformationOnlineModel;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM