C# 在ASP中获取数据库记录时,如何向gridview添加自定义数据字段?

C# 在ASP中获取数据库记录时,如何向gridview添加自定义数据字段?,c#,asp.net,C#,Asp.net,我正在用名为Students的数据库表的结果填充asp中的网格。students表包含PointsNeared和pointsPossible列。我需要根据PointsNed/pointsPossible的百分比计算字母等级。我在一个叫做“成绩”的班上做这个。如何获取当前学生的PointsNeed和pointsPossible值,然后将计算出的letterGrade添加到网格中 以下是我的方法: protected void Page_Load(object sender, EventArgs

我正在用名为Students的数据库表的结果填充asp中的网格。students表包含PointsNeared和pointsPossible列。我需要根据PointsNed/pointsPossible的百分比计算字母等级。我在一个叫做“成绩”的班上做这个。如何获取当前学生的PointsNeed和pointsPossible值,然后将计算出的letterGrade添加到网格中

以下是我的方法:

 protected void Page_Load(object sender, EventArgs e)
        {
            string connstring;
            connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
            SqlConnection conn = new SqlConnection(connstring);
            SqlCommand cmd = new SqlCommand("GetStudents", conn);

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            conn.Open();

            DataSet ds = new DataSet();
            adapter.Fill(ds, "dbo.Students");
            DataTable dt = new DataTable();
            dt.Columns.Add("letterGrade", typeof(string));

            Grades studentGrade = new Grades();
            studentGrade.pointsEarned = ???;
            studentGrade.pointsPossible = ???;
            string studentLetterGrade = studentGrade.calculate();

            //How do I add studentLetterGrade as the letterGrade column?

            StudentGrid.DataSource = ds;
            StudentGrid.DataBind();

            conn.Close();
            conn.Dispose();
        }
这是我的表格:

<asp:SqlDataSource ID="GetStudents" runat="server" ConnectionString="<%$ ConnectionStrings:dbConn %>" SelectCommand="dbo.GetStudents" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
        <asp:GridView ID="StudentGrid" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:CommandField ShowSelectButton="False" />
                <asp:BoundField DataField="studentId" HeaderText="ID" />
                <asp:BoundField DataField="firstName" HeaderText="First Name" />
                <asp:BoundField DataField="lastName" HeaderText="Last Name" />
                <asp:BoundField DataField="semester" HeaderText="Semester" />
                <asp:BoundField DataField="semesterYear" HeaderText="Year" />
                <asp:BoundField DataField="letterGrade" HeaderText="Grade" />
            </Columns>
        </asp:GridView>

有很多方法可以做到这一点,最简单的方法是计算db存储过程本身的百分比,然后检索并绑定到网格


否则,如果您不希望修改当前存储过程,并且希望在从codebehind绑定期间进行修改,则必须使用gridview rowdatabound事件,逐个绑定所有列,并根据条件修改值(如果需要)。

是的,我可以计算查询中的百分比,但我还需要根据百分比(A、B、C、D、F)计算字母等级,这是在我的等级类中完成的。@ShoeLace1291-使用gridview rowdatabound事件,当数据行绑定到gridview控件中的数据时,将触发此事件,这将允许您在绑定到grid时修改数据。。这将帮助您开始。