Accessing SQL Server Database in Editable GridView

本文详细介绍了如何使用ADO.NET框架访问SQL Server数据库,包括使用GridView进行数据绑定,实现增删改操作,并通过Webform页面与GridView结合进行数据编辑。

Introduction

In this article,we are going to discuss how to access the SQL Server Database using ADO.NET framework. Topics covered in this article include :

  • Accessing Database using ADO.NET
  • GridView data binding
  • Using GridView template to implement update, delete, insert operation on database tables



1. Background Knowledge


ADO.NET Overview



Connection 

Establishes a connection to a specific data source. The base class for all Connection objects is the DbConnection class.

Command 

Executes a command against a data source. Exposes Parameters and can execute in the scope of a Transaction from a Connection. The base class for allCommand objects is the DbCommand class.

DataReader 

Reads a forward-only, read-only stream of data from a data source. The base class for all DataReader objects is the DbDataReader class.

DataAdapter

Populates a DataSet and resolves updates with the data source. The base class for all DataAdapter objects is the DbDataAdapter class.

DataSet 

The DataSet represents a complete set of data, including related tables, constraints, and relationships among the tables. An ADO.NET DataSet contains a collection of zero or more tables represented by DataTable objects. 

Accessing SQL Server Database

       Fetch Database Table using DataSet

public DataSet GetDataSet()
{
    string strCon = "Data Source =(local);Initial Catalog = StevensUniversity;
    IntegratedSecurity = True";
    string strQuery = "Select * from Student"
    SqlConnection con = new SqlConnection(strCon);
    con.Open();
    SqlCommand cmd = new SqlCommand(strQuery,con);
    DataSetds = new DataSet();
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    adp.Fill(ds);
    con.Close();
    return ds;
}

Update Operation on Database 

public void RowDelete()
{     
    string strDelete = "Delete From Student where StudentID = 1000"    
    string strUpdate = "Update Student Set StudentName = 'Calvin Klein' Where StudentID = '1001'"    
    SqlConnection con = new SqlConnection(strCon);   
    con.Open();
    SqlCommand cmdDelete = new SqlCommand(strDelete, con);
    SqlCommand cmdUpdate = new SqlCommand(strUpdate, con);
    cmdDelete.ExecuteNonQuery();
    cmdUpdate.ExecuteNonQuery();
    con.Close();
}

2. Using GridView 


Webform Page


Step 1 -  Build an ASP.NET GridView with RowEditing, RowCancelingEdit, RowUpdating, Row Deleting , RowCommand and RowDataBound events

<asp:GridView ID="grdStudent" runat="server" AutoGenerateColumns="False" 
    DataKeyNames="StudentID" ShowFooter="True"
    OnRowEditing="grdStudent_RowEditing"
    OnRowCancelingEdit="grdStudent_RowCancelingEdit"
    OnRowUpdating="grdStudent_RowUpdating"
    OnRowDeleting="grdStudent_RowDeleting" 
    OnRowCommand="grdStudent_RowCommand"
    OnRowDataBound="grdStudent_RowBound" CellPadding="4" ForeColor="#333333" 
    GridLines="None" >
</asp:GridView>

Step 2 - Add CommandField and TemplateField

CommandField for delete command,  ItemTemplate for bindging and displaying data, EditItemTemplate for editing items, and Footer Template for inserting items

<Columns>                                                                                                                                       <asp:CommandField ShowEditButton="True"/>                                                                                          
    <asp:TemplateField ShowHeader="False">
        <ItemTemplate>
            <asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
        </ItemTemplate>
        <FooterTemplate>
            <asp:LinkButton ID="lnkInsert" runat="server" CausesValidation="False" CommandName="Insert" Text="Insert">
            </asp:LinkButton>   
       </FooterTemplate>
   </asp:TemplateField>
 
   <asp:TemplateField HeaderText="StudentID">                                                                                          
       <ItemTemplate>
           <asp:Label ID="lblStudentID" runat="server" Text='<%# Eval("StudentID")%>'></asp:Label>
       </ItemTemplate>                                                                                                                  
       <EditItemTemplate>
        <asp:TextBox runat="server" ID="txtStudentID" Text='<%# Eval("StudentID")%>'></asp:TextBox>
       </EditItemTemplate>                                                                                    
       <FooterTemplate>
            <asp:TextBox runat="server" ID="txtNewStudentID" Text='<%# Eval("StudentID") %>'></asp:TextBox>
       </FooterTemplate>                                                                                                                   
   </asp:TemplateField>                                                                                                                  
</Columns>


Code-Behind

Step 1 - Initialize GridView

public DataSet GetDataSet(string strQuery)
{
    SqlConnection con = new SqlConnection(strCon);
    con.Open();
    SqlCommand cmd = new SqlCommand(strQuery, con);
    DataSet ds = new DataSet();
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    adp.Fill(ds);
    con.Close();
    return ds;
}
public void BindData()
{
    grdStudent.DataSource = GetDataSet("Select * from Student");
    grdStudent.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindData();
    }
}
<p>
	<span style="white-space:pre"></span><span style="white-space:pre"></span>Step 1 - Binding Data
</p>
<pre name="code" class="csharp">public void grdStudent_RowBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList ddlGender = (DropDownList)e.Row.FindControl("ddlGender");
        Label lblGender = (Label)e.Row.FindControl("lblGender");
        //[Bug]Will get null reference exception if fail to examine the value of ddlGender
        if (ddlGender != null)
        {
            ddlGender.DataSource = GetDataSet("Select distinct Gender from Student");
            ddlGender.DataTextField = "Gender";
            ddlGender.DataValueField = "Gender";
            ddlGender.DataBind();
        }
    }
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        //[Bug]Will get null reference exception if using following fetch control method
        //DropDownList ddlNewGender = (DropDownList)grdStudent.FooterRow.FindControl("ddlNewGender");
        DropDownList ddlNewGender = (DropDownList)e.Row.FindControl("ddlNewGender");
        if (ddlNewGender != null)
        {
            ddlNewGender.DataSource = GetDataSet("Select distinct Gender from Student");
            ddlNewGender.DataTextField = "Gender";
            ddlNewGender.DataValueField = "Gender";
            ddlNewGender.DataBind();
            ddlNewGender.Items.Insert(0, "--Select--");
        }
    }
}

Step 3 - Edit/Cancel Edit Command

public void grdStudent_RowEditing(object sender, GridViewEditEventArgs e)
{
    grdStudent.EditIndex = e.NewEditIndex; 
    BindData();
}
public void grdStudent_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    grdStudent.EditIndex = -1;
    BindData();
}

Step 4 - Update/Delete/Insert Data

public void grdStudent_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    string StudentID = grdStudent.DataKeys[e.RowIndex].Values[0].ToString();
    string NewStudentID = ((TextBox)grdStudent.Rows[e.RowIndex].FindControl("txtStudentID")).Text;
    string NewDepartment =((TextBox)grdStudent.Rows[e.RowIndex].FindControl("txtDepartment")).Text;
    string NewStudentName = ((TextBox)grdStudent.Rows[e.RowIndex].FindControl("txtStudentName")).Text;
    string NewGender = ((DropDownList)grdStudent.Rows[e.RowIndex].FindControl("ddlGender")).SelectedItem.ToString();
    string NewEnrollmentDate = ((TextBox)grdStudent.Rows[e.RowIndex].FindControl("txtEnrollmentDate")).Text;
    string strUpdate = "Update Student set StudentID = '" + NewStudentID + "', Department='" + NewDepartment + "', StudentName='" + NewStudentName + "', Gender='" +  NewGender  + "', EnrollmentDate='" + NewEnrollmentDate + "' where StudentID = " + StudentID;                                                      SqlConnection con = new SqlConnection(strCon);
    con.Open();
    SqlCommand cmd = new SqlCommand(strUpdate,con);
    cmd.ExecuteNonQuery();
    con.Close();
    grdStudent.EditIndex = -1;
    BindData();
}


public void grdStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    //[Bug]Will get null reference exception if using following fetch control method
    //string StudentID= ((TextBox)grdStudent.Rows[e.RowIndex].FindControl("txtStudentID")).Text;
    string StudentID = grdStudent.DataKeys[e.RowIndex].Values[0].ToString();                                                                                                                string strDelete = "Delete From Student where StudentID = " + StudentID;         
    SqlConnection con = new SqlConnection(strCon);
    con.Open();
    SqlCommand cmd = new SqlCommand(strDelete, con);
    cmd.ExecuteNonQuery();
    con.Close();
    BindData();
}


public void grdStudent_RowCommand(object sender, GridViewCommandEventArgs e)
{
   if (e.CommandName.Equals("Insert"))
   {
        string NewStudentID = ((TextBox)grdStudent.FooterRow.FindControl("txtNewStudentID")).Text;
        string NewDepartment = ((TextBox)grdStudent.FooterRow.FindControl("txtNewDepartment")).Text;
        string NewStudentName = ((TextBox)grdStudent.FooterRow.FindControl("txtNewStudentName")).Text;
        string NewGender = (DropDownList)grdStudent.FooterRow.FindControl("ddlNewGender")).SelectedItem.ToString();
        string NewEnrollmentDate = ((TextBox)grdStudent.FooterRow.FindControl("txtNewEnrollmentDate")).Text;
        string strInsert = "Insert into Student (StudentID, Department, StudentName, Gender,EnrollmentDate)Values ('" + NewStudentID + "','"                                                                        +  NewDepartment + "','"+  NewStudentName + "','"+ NewGender+ "','" + NewEnrollmentDate + "')";
        SqlConnection con = new SqlConnection(strCon);
        con.Open();
        SqlCommand cmd = new SqlCommand(strInsert, con);
        cmd.ExecuteNonQuery();
        con.Close();
        BindData();
    }
}







                
内容概要:本文围绕“基于改进滑模控制的永磁同步电机调速系统模型研究”展开,重点介绍在Simulink环境中构建和仿真永磁同步电机(PMSM)调速系统的方法,采用改进滑模控制策略以提升系统鲁棒性与动态性能。文中系统阐述了控制算法的设计原理、系统建模流程、关键模块搭建及仿真结果分析,旨在复现高水平科研成果(SCI/EI级别),并通过仿真实验验证所提控制策略的有效性。该研究属于电机控制与电力电子领域的前沿方向,对高精度伺服系统、新能源汽车电驱动系统等实际应用场景具有重要的理论指导和工程参考价值; 适合人群:具备自动控制理论基础和Simulink/MATLAB仿真能力,从事电气工程、自动化、电力电子等相关专业的研究生、科研人员及工程技术人员,尤其适合致力于复现高水平学术论文成果的研究者; 使用场景及目标:①深入学习永磁同步电机矢量控制与滑模变结构控制的核心原理与建模方法;②复现并理解SCI/EI期刊中先进电机控制算法的技术细节;③开展电机控制系统仿真研究,优化控制参数,提升系统抗干扰能力、稳态精度与动态响应性能; 阅读建议:建议结合文中提及的完整资源包(含Simulink模型、MATLAB代码、详细说明文档)进行实践操作,重点关注控制策略的实现逻辑与仿真调试过程,注重理论推导与仿真实验相结合,同时参考同类高水平研究以拓展技术视野。
内容概要:本文提出了一种基于数据驱动的Koopman算子与递归神经网络(RNN)相结合的模型线性化方法,旨在解决纳米定位系统中因强非线性、迟滞和蠕变效应导致的建模困难问题。该方法通过Koopman算子将非线性动态系统映射至高维线性空间,利用RNN学习系统的时间序列演化特征,从而实现对复杂动态行为的精确建模与预测,并进一步集成于模型预测控制(MPC)框架中,显著提升了纳米定位系统的控制精度、动态响应能力与运行稳定性。整个算法体系在Matlab平台上完成代码实现与仿真实验验证,展示了良好的控制性能与工程应用潜力。; 适合人群:具备控制理论、非线性系统建模、机器学习及智能控制基础,从事精密仪器控制、高端制造装备研发、自动化系统设计等领域的研究生、科研人员及工程技术开发者。; 使用场景及目标:①应对扫描探针显微镜、光刻机、超精密加工平台等纳米级定位设备中的非线性建模挑战;②提升高精度运动系统的实时预测控制性能,抑制迟滞与蠕变带来的定位误差;③为数据驱动的非线性系统线性化与先进控制策略(如MPC)的融合提供可复现、可扩展的技术范例。; 阅读建议:建议读者结合提供的Matlab代码,深入理解Koopman观测矩阵构造、RNN网络训练流程及MPC控制器设计之间的协同机制,重点关注数据预处理、特征提取、模型训练与闭环控制仿真的完整链路,以便在相似高精度控制系统中进行迁移与优化应用。
内容概要:本文系统研究了基于动态三维环境下的Q-Learning算法在无人机自主避障路径规划中的应用,旨在通过强化学习实现无人机在复杂、动态空间中的智能决策与安全飞行。研究构建了完整的Q-Learning模型框架,涵盖状态空间定义、动作策略设计与奖励函数构建,重点提升了算法在存在移动障碍物场景下的路径规划能力与实时避障性能。通过Matlab仿真平台实现了算法的全流程建模与验证,展示了其在路径最优性、环境适应性与运行稳定性方面的优势,并为后续多机协同、城市密集环境等高级应用场景提供了可扩展的技术基础与代码支持。; 适合人群:具备一定编程基础和控制理论知识,从事无人机导航、智能优化算法或强化学习相关研究的科研人员及研究生。; 使用场景及目标:① 掌握Q-Learning算法在三维动态路径规划中的建模与实现方法;② 学习如何将强化学习技术应用于实际工程问题如无人机自主避障;③ 为深入研究多智能体协同、复杂非结构化环境下的路径规划提供算法原型与仿真基础; 阅读建议:建议读者结合提供的Matlab代码进行仿真实验,深入理解状态表示与奖励机制的设计逻辑,尝试调整算法参数或引入新的动态障碍物模式以评估鲁棒性,并可进一步对比其他智能算法(如DQN、A*、DWA等)在相同环境下的性能差异。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值