执行效果
前台代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>对DataSet中的数据进行操作</title>
<style >
body:{margin-top:0px}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style=" font-size :9pt">
<tr>
<td style="height: 126px">
<asp:GridView ID="GridView1" runat="server" >
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
后台代码
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//bind();
SqlConnection myConn = GetConnection();
myConn.Open();
string sqlStr = "select * from t001 ";
SqlDataAdapter myDa = new SqlDataAdapter(sqlStr, myConn);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
for (int i = 0; i <= myDs.Tables[0].Rows.Count - 1; i++)
{
myDs.Tables[0].Rows[i]["text"] = SubStr(Convert.ToString(myDs.Tables[0].Rows[i]["text"]), 5);
}
GridView1.DataSource = myDs;
GridView1.DataKeyNames = new string[] { "bukrs" };
GridView1.DataBind();
myDa.Dispose();
myDs.Dispose();
myConn.Close();
}
}
public SqlConnection GetConnection()
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection myConn = new SqlConnection(myStr);
return myConn;
}
public string SubStr(string sString, int nLeng)
{
if (sString.Length <= nLeng)
{
return sString;
}
string sNewStr = sString.Substring(0, nLeng);
sNewStr = sNewStr + "...";
return sNewStr;
}
}
配置代码
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\DataBase\sap.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"/>
</appSettings>
<connectionStrings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
</configuration>
注意:
for (int i = 0; i <= myDs.Tables[0].Rows.Count - 1; i++)
{
myDs.Tables[0].Rows[i]["text"] = SubStr(Convert.ToString(myDs.Tables[0].Rows[i]["text"]), 5);
}
是对myds循环修改内容的,将过长内容使用*号体现在table中