下面是一個新增資料到資料庫的方法
stringsql=連線字串;
publicboolinsertcomment(stringtype,stringid,stringname,stringbody)
{
stringsqlstr="insertintocommentInfo("+type+",sender,time,body)values("+id+",""+name+"",default,""+body+"")";
try
using(SqlConnectionconn=newSqlConnection(sql))
SqlCommandcmd=newSqlCommand(sqlstr,conn);
conn.Open();
cmd.ExecuteNonQuery();
}
returntrue;
catch(Exception)
throw;
returnfalse;
下面是default.aspx裡的datagridview的程式碼
<asp:GridViewID="GridView1"runat="server"AutoGenerateColumns="False"DataKeyNames="id"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundFieldDataField="id"HeaderText="id"InsertVisible="False"ReadOnly="True"
SortExpression="id"/>
<asp:BoundFieldDataField="name"HeaderText="name"SortExpression="name"/>
<asp:BoundFieldDataField="pwd"HeaderText="pwd"SortExpression="pwd"/>
</Columns>
</asp:GridView>
<asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ConnectionStrings:WORKSHOP.MDFConnectionString%>"
SelectCommand="SELECT*FROM[admin]"></asp:SqlDataSource>
如果需要手動幫頂資料來源相應的default.aspx.cs檔案裡的資料幫頂是以下程式碼
this.GridView1.DataSource=this.SqlDataSource1;
this.SqlDataSource1.DataBind();
下面是一個新增資料到資料庫的方法
stringsql=連線字串;
publicboolinsertcomment(stringtype,stringid,stringname,stringbody)
{
stringsqlstr="insertintocommentInfo("+type+",sender,time,body)values("+id+",""+name+"",default,""+body+"")";
try
{
using(SqlConnectionconn=newSqlConnection(sql))
{
SqlCommandcmd=newSqlCommand(sqlstr,conn);
conn.Open();
cmd.ExecuteNonQuery();
}
returntrue;
}
catch(Exception)
{
throw;
returnfalse;
}
}
下面是default.aspx裡的datagridview的程式碼
<asp:GridViewID="GridView1"runat="server"AutoGenerateColumns="False"DataKeyNames="id"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundFieldDataField="id"HeaderText="id"InsertVisible="False"ReadOnly="True"
SortExpression="id"/>
<asp:BoundFieldDataField="name"HeaderText="name"SortExpression="name"/>
<asp:BoundFieldDataField="pwd"HeaderText="pwd"SortExpression="pwd"/>
</Columns>
</asp:GridView>
<asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ConnectionStrings:WORKSHOP.MDFConnectionString%>"
SelectCommand="SELECT*FROM[admin]"></asp:SqlDataSource>
如果需要手動幫頂資料來源相應的default.aspx.cs檔案裡的資料幫頂是以下程式碼
this.GridView1.DataSource=this.SqlDataSource1;
this.SqlDataSource1.DataBind();