繁体   English   中英

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

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

我有一个用于学生记录的视觉工作室项目,这些记录来自我们的在线注册应用程序。 然后数据库保存它。 但问题是当我尝试使用我的其他应用程序检索它时,我的 datagridview 没有从数据库中检索所有记录。 换句话说,我们的在线应用程序在线收集数据,而另一个应用程序用于显示数据以进行处理。

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;
    }
}

您的代码需要一些改进。 您不需要手动添加行。 干脆做。

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

对于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);
    }
}

如果您需要将对象排成一行,那么您可以这样做(例如在索引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