【问题标题】:rowindex always starting from zero onwards...why?rowindex 总是从零开始...为什么?
【发布时间】:2014-03-25 03:01:25
【问题描述】:

这是我的代码..在编辑和删除行索引时总是取零开始...删除命令根本不起作用....如果我尝试仅在第二行开始编辑任何内容...删除命令根本不起作用..我认为这是因为行索引..请任何人帮助我提前感谢....

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 Manager_Payments : System.Web.UI.Page
{
    //SqlConnection con =new SqlConnection("Data Source=sqlexpress;Initial Catalog=isoqrmssys;User ID=sa;password=123456;Integrated Security=True");

    Business BL = new Business();

     //protected Int64 stf_ID, vmember;
    //protected DateTime SRDT;
   private System.Drawing.Color a;
    string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();

    protected void Page_Load(object sender, EventArgs e)
    {
        loadgridview();
    }

    private void loadgridview()
    {

        SqlConnection con = new SqlConnection(myStr);
        SqlCommand cmd = new SqlCommand("select * from CustomerProfMain", con);
        //string sql = "SELECT * FROM CustomerProfMain";
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        con.Open();
        DataSet ds = new DataSet();
        sda.Fill(ds);
        //return ds.Tables[0];
        Grd_View.DataSource = ds.Tables[0];
        Grd_View.DataBind();
        con.Close();
    }


    protected void Grd_View_RowCommand(Object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
            {

                int index = Grd_View.SelectedIndex;
                if (e.CommandName == "Edit")
                {
                    //string RowIndex = int.Parse(e.CommandArgument.ToString());
                   // Session["rowid"] = RowIndex;
                    DataTable dt = new DataTable();
                    SqlConnection con = new SqlConnection(myStr);
                    SqlCommand cmd = new SqlCommand("Select * from CustomerProfMain where CustomerCode='" + e.CommandArgument.ToString() + "'", con);
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    con.Open();
                    DataSet ds = new DataSet();
                    sda.Fill(ds);
                    dt=ds.Tables[0];
                    TextBox1.Text = dt.Rows[0]["CustomerName"].ToString();
                    TextBox2.Text=dt.Rows[0]["Address"].ToString();
                    TextBox3.Text=dt.Rows[0]["TellNo"].ToString();
                    TextBox4.Text=dt.Rows[0]["FaxNo"].ToString();
                    TextBox5.Text=dt.Rows[0]["Email"].ToString();
                    Button1.Text = "Update";

                }
                if (e.CommandName == "Delete")
                {
                    int RowIndex = int.Parse(e.CommandArgument.ToString());
                   Session["rowid"] = RowIndex;
                   // DataTable dt = new DataTable();
                    SqlConnection con = new SqlConnection(myStr);
                    SqlCommand cmd = new SqlCommand("Delete from CustomerProfMain where CustomerCode='" + RowIndex + "' ", con);
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();


                }
              }
    protected void Grd_View_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
    protected void Grd_View_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    }
    protected void Grd_View_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Button1.Text == "Add")
        {
            string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
            SqlConnection con = new SqlConnection(myStr);
            con.Open();
            string sql = string.Empty;
            sql = "insert into CustomerProfMain(CustomerName,Address,TellNo,FaxNo,Email) values('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "','" + TextBox3.Text.Trim() + "','" + TextBox4.Text.Trim() + "','" + TextBox5.Text.Trim() + "') ";
            SqlCommand cmd = new SqlCommand(sql, con);

            cmd.ExecuteNonQuery();
            con.Close();
            TextBox1.Text = "";
            TextBox2.Text = "";
            TextBox3.Text = "";
            TextBox4.Text = "";
            TextBox5.Text = "";
            Button1.Text = "Add";
            loadgridview();
        }
        if (Button1.Text == "Update")
        {
            string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
            SqlConnection con = new SqlConnection(myStr);
            con.Open();
            string sql = string.Empty;
            sql = "update CustomerProfMain set CustomerName='" + TextBox1.Text.Trim() + "',Address='" + TextBox2.Text.Trim() + "',TellNo='" + TextBox3.Text.Trim() + "',FaxNo='" + TextBox4.Text.Trim() + "',Email='" + TextBox5.Text.Trim() + "' where CustomerCode='" + Session["rowid"] + "'";
            SqlCommand cmd = new SqlCommand(sql, con);

            cmd.ExecuteNonQuery();
            con.Close();
            TextBox1.Text = "";
            TextBox2.Text = "";
            TextBox3.Text = "";
            TextBox4.Text = "";
            TextBox5.Text = "";
            Button1.Text = "Add";
            loadgridview();
        }

    }



}



"<asp:GridView ID="Grd_View" ShowFooter="True" runat="server" OnRowEditing="Grd_View_RowEditing" AutoGenerateColumns="False"
                     DataKeyNames="CustomerCode" cellpadding="4" OnRowCommand="Grd_View_RowCommand"                  GridLines="None" 
                    AllowPaging="True" AllowSorting="True" CssClass="style2" ForeColor="#333333" Width="569px" OnRowDataBound="Grd_View_RowDataBound" OnRowDeleting="Grd_View_RowDeleting">
                    <FooterStyle BackColor="#555555" ForeColor="White" Font-Bold="True" />
                    <Columns>
                        <asp:BoundField DataField="CustomerCode" HeaderText="CustomerCode" InsertVisible="False"
                            ReadOnly="True" SortExpression="CustomerCode" />

                        <asp:BoundField DataField="CustomerName" HeaderText="CustomerName" SortExpression="CustomerName" />
                        <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                        <asp:BoundField DataField="TellNo" HeaderText="TellNo" SortExpression="TellNo" />
                        <asp:BoundField DataField="FaxNo" HeaderText="FaxNo" SortExpression="FaxNo" />
                        <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
                        <asp:CommandField ShowEditButton="true" SelectText="Edit" />
                        <asp:CommandField ShowDeleteButton="true" SelectText="Delete" />

                    </Columns>
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <PagerStyle BackColor="#777777" ForeColor="White" HorizontalAlign="Center" />
                    <HeaderStyle BackColor="#555555" Font-Bold="True" ForeColor="White" />
                    <EditRowStyle BackColor="#999999" />
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

                </asp:GridView>

"

【问题讨论】:

  • 请注意您的代码存在 SQL 注入漏洞。
  • 你确定数据库中的CustomerCode和grid的rowindex一样吗?能否请您显示网格的 aspx 代码...?
  • 傻瓜有道理,我的回答假设一切都是直截了当的,this 应该有助于解决“SQL 注入漏洞” - paqogomez。
  • @chrish549 请不要发布“aspx 代码作为答案”。编辑您的问题并发布。如果您想将e.CommandArgument 设为CustomerCode,则必须进行设置。你没有在后面的代码中设置它,因为我可以看到你的 cs 代码。所以我想知道你是如何在你的 aspx 代码中设置它的。例如:CommandArgument='&lt;%# Eval('CustomerCode') %&gt;' 。无论如何,我也无法将您的 aspx 视为答案 :-)
  • 您能在问题下方看到编辑按钮吗?编辑您的问题。发布您的代码。无需将代码放在注释框中 ....Please refer this too 如果你没有设置 CommandArgument 你会得到 e.CommandArgument 作为从零开始升序的整数

标签: c# asp.net


【解决方案1】:

用此代码替换您的网格视图

 <asp:GridView ID="Grd_View" ShowFooter="True" runat="server" OnRowEditing="Grd_View_RowEditing" AutoGenerateColumns="False"
                DataKeyNames="CustomerCode" CellPadding="4" OnRowCommand="Grd_View_RowCommand" GridLines="None"
                AllowPaging="True" AllowSorting="True" CssClass="style2" ForeColor="#333333" Width="569px" OnRowDataBound="Grd_View_RowDataBound" OnRowDeleting="Grd_View_RowDeleting">
                <FooterStyle BackColor="#555555" ForeColor="White" Font-Bold="True" />
                <Columns>
                    <asp:BoundField DataField="CustomerCode" HeaderText="CustomerCode" InsertVisible="False"
                        ReadOnly="True" SortExpression="CustomerCode" />

                    <asp:BoundField DataField="CustomerName" HeaderText="CustomerName" SortExpression="CustomerName" />
                    <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                    <asp:BoundField DataField="TellNo" HeaderText="TellNo" SortExpression="TellNo" />

                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:LinkButton ID="btnEdit" runat="server" CommandArgument='<%#Eval("CustomerCode")%>' CommandName="Edit" Text="Edit">
                            </asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:LinkButton ID="btnDelete" runat="server" CommandArgument='<%#Eval("CustomerCode")%>' CommandName="Delete" Text="Delete">
                            </asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>

                </Columns>
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <PagerStyle BackColor="#777777" ForeColor="White" HorizontalAlign="Center" />
                <HeaderStyle BackColor="#555555" Font-Bold="True" ForeColor="White" />
                <EditRowStyle BackColor="#999999" />
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

            </asp:GridView>

你没有设置CommandArgument在这里我们将它设置为CommandArgument='&lt;%#Eval("CustomerCode")%&gt;'到你的编辑按钮和删除按钮

【讨论】:

    【解决方案2】:

    尝试执行以下操作...仅当不是回发时才在页面加载时绑定网格...

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
            loadgridview();
    }
    

    然后在命令事件处理程序的末尾重新绑定网格,为了清楚起见,我将删除一些数据访问逻辑...

    protected void Grd_View_RowCommand(Object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
            {
    
                int index = Grd_View.SelectedIndex;
                if (e.CommandName == "Edit")
                {
                   //...
                   loadgridview();
                }
                if (e.CommandName == "Delete")
                {
                   //...
                   loadgridview();
                }
              }
    

    【讨论】:

    • 发生类似的事情先生...仍然行索引值显示“0”
    • 因为,你还没有发布相关的 HTML 我不得不问....e.CommandArgument 是什么?谁在触发该命令?
    • 阅读我在 cmets 中发布的 msdn 链接以获得我的答案 e.CommandArgument 应该由程序员设置为字符串。
    • @Leo 哦,是的,我猜你已经在问他设置了什么
    【解决方案3】:

    试试这个并将 GridView 的 AutoPostback 属性设置为 true

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            loadgridview();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      相关资源
      最近更新 更多