<%@ Page Language="c#" debug="true"%>
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.SqlClient" %><script runat="server">//make first sql 
String sql = "";
String strCnn = "Data Source=localhost;Initial Catalog=0808;User Id=sa;Password=password;";
//create a datasource function
public ICollection CreateDataSource () {
SqlConnection conn = new SqlConnection(strCnn);SqlDataAdapter db_sqladaptor = new SqlDataAdapter(sql,conn);DataSet ds = new DataSet();
db_sqladaptor.Fill(ds,"MyDataResult");DataView myView = ds.Tables["MyDataResult"].DefaultView;
return myView;
}
//do page loadpublic void Page_Load(Object sender, EventArgs e) {
strCnn = "Data Source=localhost;Initial Catalog=0808;User Id=sa;Password=password;";if (!IsPostBack) 
{
sql = "Select * FROM sh_configration";
sh_configration.DataSource = CreateDataSource();
sh_configration.DataBind();
}} public void Page_Grid(Object sender, DataGridPageChangedEventArgs e) 
{
sql = "Select * FROM sh_configration";
// Set CurrentPageIndex to the page the user clicked.
sh_configration.CurrentPageIndex = e.NewPageIndex;// Rebind the data. 
sh_configration.DataSource = CreateDataSource();
sh_configration.DataBind();}public void sh_configration_Edit(Object sender, DataGridCommandEventArgs e) 
{
sql = "Select * FROM sh_configration"; sh_configration.EditItemIndex = e.Item.ItemIndex;
sh_configration.DataSource = CreateDataSource();
sh_configration.DataBind();}public void sh_configration_Cancel(Object sender, DataGridCommandEventArgs e) 
{
sql = "Select * FROM sh_configration";
sh_configration.EditItemIndex = -1;
sh_configration.DataSource = CreateDataSource();
sh_configration.DataBind();}public void sh_configration_Update(Object sender, DataGridCommandEventArgs e) 
{
string city = ((TextBox)e.Item.Cells[1].Controls[1]).Text;
string price = ((TextBox)e.Item.Cells[2].Controls[1]).Text;
string quickprice = ((TextBox)e.Item.Cells[3].Controls[1]).Text;
SqlConnection connUpdate = new SqlConnection(strCnn);
connUpdate.Open();
String sql_edit = "UPDATE sh_configration " +
"SET city = '" + city.Replace("'","''")+ "'," +
"price = '" + price.Replace("'","''")+ "'," +
"quickprice = '" + quickprice.Replace("'","''")+ "'" +
" WHERE id = " + e.Item.Cells[0].Text;SqlCommand sqlCommandUpdate = new SqlCommand(sql_edit,connUpdate);
sqlCommandUpdate.ExecuteNonQuery();
connUpdate.Close();sql =  "Select * FROM sh_configration";
sh_configration.EditItemIndex = -1;
sh_configration.DataSource = CreateDataSource();
sh_configration.DataBind();}public void sh_configration_Delete(Object sender, DataGridCommandEventArgs e) {SqlConnection connDel = new SqlConnection(strCnn);
connDel.Open();
String sql_Del = "DELETE FROM sh_configration " +
" WHERE id = " + e.Item.Cells[0].Text;SqlCommand sqlCommandDel = new SqlCommand(sql_Del,connDel);
sqlCommandDel.ExecuteNonQuery();
connDel.Close();sql =  "Select * FROM sh_configration";
sh_configration.EditItemIndex = -1;
sh_configration.DataSource = CreateDataSource();
sh_configration.DataBind();}public void AddPublisher(Object sender, EventArgs E)
 {
SqlConnection mySqlCon;
mySqlCon=new SqlConnection("server=localhost;uid=sa;pwd=password;database=0808");String myinsertCmd = "insert into sh_configration( city,price,quickprice ) values (@city,@price,@quickprice)"; 
SqlCommand mySqlCom = new SqlCommand(myinsertCmd, mySqlCon); 
mySqlCom.Parameters.Add(new SqlParameter("@city", SqlDbType.NVarChar, 50)); 
mySqlCom.Parameters["@city"].Value = city.Text; 
mySqlCom.Parameters.Add(new SqlParameter("@price", SqlDbType.NVarChar, 50)); 
mySqlCom.Parameters["@price"].Value = price.Text; 
mySqlCom.Parameters.Add(new SqlParameter("@quickprice", SqlDbType.NVarChar, 50)); 
mySqlCom.Parameters["@quickprice"].Value = quickprice.Text; 
mySqlCom.Connection.Open(); 
mySqlCom.ExecuteNonQuery(); 
mySqlCom.Connection.Close(); 
sql =  "Select * FROM sh_configration";
sh_configration.EditItemIndex = -1;
sh_configration.DataSource = CreateDataSource();
sh_configration.DataBind();} 
</script>

解决方案 »

  1.   

    <form runat="server"><asp:DataGrid id="sh_configration" runat="server"
    BorderColor="green" 
    Width="640" 
    PageSize="5" 
    AllowPaging="true" 
    OnPageIndexChanged="Page_Grid" 
    PagerStyle-PrevPageText="前页"
    PagerStyle-NextPageText="后页"
    PagerStyle-HorizontalAlign="Right"
    BorderWidth="1"
    CellPadding="3"
    AutoGenerateColumns="false"
    ShowHeader="true" 
    Visible="true" OnEditCommand="sh_configration_Edit" 
    OnCancelCommand="sh_configration_Cancel" 
    OnUpdateCommand="sh_configration_Update" 
    OnDeleteCommand="sh_configration_Delete"><HeaderStyle BorderColor="White" BackColor="#FFCC00" 
    ForeColor="Black" 
    Font-Bold="true" 
    Font-Name="Arial" 
    Font-Size="9" HorizontalAlign="Center"
    /><ItemStyle   BorderColor="" 
    BackColor="#FFFFF0" 
    ForeColor="Black" 
    Font-Name="Arial" 
    Font-Size="9" 
    Font-Bold="False" HorizontalAlign="Center"/><EditItemStyle   BorderColor="" 
    BackColor="#FFFFF0" 
    ForeColor="Black" 
    Font-Name="Arial" 
    Font-Size="9" 
    Font-Bold="False" HorizontalAlign="Center"/><PagerStyle Mode="NumericPages" Font-Size="8"/><Columns><asp:BoundColumn HeaderText="ID" ReadOnly="true" DataField="id"/><asp:TemplateColumn><HeaderTemplate>
    <b>城市 </b>
    </HeaderTemplate><ItemTemplate>
    <asp:Label
    Text='<%# DataBinder.Eval(Container.DataItem, "city").ToString().Trim() %>'
    runat="server"/>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox id="city" Text='<%# DataBinder.Eval(Container.DataItem, "city").ToString().Trim() %>' runat="server" Width="100%"/>
    </EditItemTemplate></asp:TemplateColumn><asp:TemplateColumn><HeaderTemplate>
    <b> 价格 </b>
    </HeaderTemplate><ItemTemplate>
    <asp:Label 
    Width="200" 
    Text='<%# DataBinder.Eval(Container.DataItem, "price").ToString().Trim() %>' 
    runat="server"/>
    </ItemTemplate><EditItemTemplate>
    <asp:TextBox id="price" Text='<%# DataBinder.Eval(Container.DataItem, "price").ToString().Trim() %>' runat="server" Width="100%"/>
    </EditItemTemplate></asp:TemplateColumn>
    <asp:TemplateColumn><HeaderTemplate>
    <b> 快递价格 </b>
    </HeaderTemplate><ItemTemplate>
    <asp:Label 
    Width="200" 
    Text='<%# DataBinder.Eval(Container.DataItem, "quickprice").ToString().Trim() %>' 
    runat="server"/>
    </ItemTemplate><EditItemTemplate>
    <asp:TextBox id="quickprice" Text='<%# DataBinder.Eval(Container.DataItem, "quickprice").ToString().Trim() %>' runat="server" Width="100%"/>
    </EditItemTemplate></asp:TemplateColumn>
    <asp:EditCommandColumn
    ButtonType="LinkButton"
    CancelText="取消"
    EditText="编辑"
    UpdateText="更新" 
     HeaderText="编辑"
    /><asp:ButtonColumn Text= "删除" CommandName="Delete"  HeaderText="删除"> </asp:ButtonColumn> </Columns></asp:DataGrid><br><br><br><br>
    增加新配送<br>
    <table width="600" border="0" cellspacing="0" cellpadding="0" align="center">
                    <tr bgcolor="#006666"> 
                      <td> 
                        <table width="600" border="0" cellspacing="1" cellpadding="2" class="p9" height="100%">
                          <tr bgcolor="#FFFFFF"> 
                            <td bgcolor="#f1f1f1" width="136" align="right">城市:</td>
                            <td width="459" bgcolor="#FEFBE2"> 
                              <asp:textbox id="city" runat="server" />
                            </td>
                          </tr>
                          <tr bgcolor="#FFFFFF"> 
                            <td bgcolor="#f1f1f1" width="136" align="right">价格:</td>
                            <td width="459" bgcolor="#FEFBE2"> 
                              <asp:textbox id="price" runat="server" onkeypress="if (event.keyCode<=47 || event.keyCode>57 ) event.returnValue = false;"/>
                            </td>
                          </tr>
                          <tr bgcolor="#FFFFFF"> 
                            <td bgcolor="#f1f1f1" width="136" align="right">快递价格:</td>
                            <td width="459" bgcolor="#FEFBE2"> 
                              <asp:textbox id="quickprice" runat="server" onkeypress="if (event.keyCode<=47 || event.keyCode>57 ) event.returnValue = false;"/>
                            </td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                  </table>
                  <div align="center">
    <asp:button Text="添加" OnClick="AddPublisher" runat="server" ID="Button1" /><br/>

                  </div>
    </form>  这是一个可以运行的编辑删除添加数据的例子,每页显示5条数据,我碰到一个问题,就是当总共有6条数据时,当我删除第六条数据时程序会报错,但是如果从第一条开始删除则没有问题!!望高手们能够指点一下!
      

  2.   

    check if the current item count is = 1//after deletion
    if (YourDataGrid1.Items.Count == 1 && YourDataGrid1.CurrentPageIndex >0 )
      YourDataGrid1.CurrentPageIndex--;//bind datagrid again
      

  3.   

    在绑定前限定当前页不超过最大页(一个例子,要做些更改)myview = ds.Tables[0].DefaultView (数据源)
    if (myview.Count!=0)
    {
      if (sh_configration.CurrentPageIndex > Math.Ceiling(myview.Count/dgList.PageSize))
      {
        sh_configration.CurrentPageIndex = 0;
      }
      if ((long)sh_configration.CurrentPageIndex*(long)sh_configration.PageSize==(long)myview.Count)
      {
        sh_configration.CurrentPageIndex -= 1;
      }
    }
      

  4.   

    To思归::
    if (YourDataGrid1.Items.Count == 1 && YourDataGrid1.CurrentPageIndex >0 )
      YourDataGrid1.CurrentPageIndex--;这段程序我具体应该加在哪里啊??
      

  5.   

    第6条在第二页上,页索引为1,删除第6条后你的页索引如果还是1,也就是还在第二页当然就会出错,遇这种情况你可以判断一下,将页索引向前一页,即可。判断的方法见 saucer(思归)老大的方法。
      

  6.   

    DataSet ds=数据来源();
    int intPageCount;
    if(ds.Tables[0].Rows.Count % dg.PageSize==0)
    intPageCount=ds.Tables[0].Rows.Count / dg.PageSize;
    else
    intPageCount=ds.Tables[0].Rows.Count / dg.PageSize + 1;
    if(dg.CurrentPageIndex > intPageCount-1 && intPageCount>0)
    dg.CurrentPageIndex=intPageCount-1;
    if(dg.CurrentPageIndex < 0)
    dg.CurrentPageIndex=0; dg.DataSource=ds.Tables[0];
    dg.DataBind();
      

  7.   

    if (YourDataGrid1.Items.Count == 1 && YourDataGrid1.CurrentPageIndex >0 )
      YourDataGrid1.CurrentPageIndex--;加在数据帮定的时候
      

  8.   

    in your DeleteCommand code
      

  9.   

    saucer(思归) 正解
    加在绑定就不好用了。鄙视灌大粪的人!