当前位置:编程学习 > C#/ASP.NET >>

请教一个GridView的问题

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns=False OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5">
            <Columns>
                   <asp:BoundField DataField="city_id" HeaderText="城市编号" />
                <asp:BoundField DataField="city" HeaderText="城市" />
                   <asp:CommandField HeaderText="编缉" ShowEditButton=True/>
                <asp:TemplateField HeaderText="删除">
                    <ItemTemplate>
                        <asp:LinkButton ID="DeleteBtn" runat="server" CausesValidation=false CommandName="Delete" OnClientClick="return confirm('确认要删除此行信息吗?')">删除</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
 </asp:GridView>

在编辑状态,我要取city列的值进行更新,但是每次都取不到,取到的值为空.
取值的语句为:
city.Value = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();]]

很奇怪的是,我取Cells[0]时,却可以取到city_id的值,
搞了一天下午,翻找了很多的贴子,搞不掂了
请各位高手指点指点,无限感激!

--------------------编程问答-------------------- Cells[0]的时候是第一个 !!
Cells[1]就是第2个了!!
也就是"城市" --------------------编程问答-------------------- GridView编辑时获取编辑框中的值
string quantity = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text; 

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "check")
        {
            string index= e.CommandArgument.ToString();
            GridViewRow row = GridView1.Rows[index];
            string id = row.Cells[1].Text;
        }
    } --------------------编程问答-------------------- 下标从0开始. --------------------编程问答-------------------- Cells[2]试试 --------------------编程问答-------------------- 0,1,2,3,4都试过了 --------------------编程问答-------------------- Cells[1].Controls[0]
问题可能出在你后边这个Controls上


Cells[1].Controls[1]或者Cells[1].findcontrol()试试
--------------------编程问答-------------------- ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text
这样应该是对的啊  调试一下 --------------------编程问答-------------------- 1,1试过了,Cells[1].Findcontrol()因为是模板列,我也不知道textbox控件的ID是什么,无法找 --------------------编程问答-------------------- 很奇怪,取第一列可以,第二列却不给我取 --------------------编程问答-------------------- city.Value   =   ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();]] 

city.Value   =   GridView1.Rows[e.RowIndex].Cells[1].Text.ToString();
你第2列根本就不是模板列,不用找他的controls集合 --------------------编程问答-------------------- city.Value       =       ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();]]   
改 
city.Value       =       GridView1.Rows[e.RowIndex].Cells[1].Text.ToString(); 
你第2列根本就不是模板列,不用找他的controls集合 
 

这样取到的还是空值啊!
而且我在编辑状态下取文本框的值,应该要用controls吧?
 
--------------------编程问答-------------------- 还有高手在吗? --------------------编程问答-------------------- 这是我做的一个例子你看看.
前台代码

<%@ 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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  OnRowEditing="GridView1_RowEditing" DataKeyNames="id" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowDataBound="GridView1_RowDataBound" OnRowUpdating="GridView1_RowUpdating">
            <Columns>
                <asp:BoundField DataField="id" HeaderText="编号" />
                <asp:TemplateField HeaderText="姓名">
                    <ItemTemplate>
                    <%# Eval("name") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtname" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="性别">
                    <ItemTemplate>
                         <%# Eval("sexshow") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddlsex" runat="server">
                        </asp:DropDownList>
                        <asp:HiddenField ID="hdfsex" runat="server" Value='<%# Eval("sex") %>' />
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="公司">
                    <ItemTemplate>
                         <%# Eval("company") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtcompany" runat="server" Text='<%# Eval("company") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:CommandField HeaderText="操作" ShowDeleteButton="True" ShowEditButton="True" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:Label ID="lbname" runat="server" Text="姓名"></asp:Label>
        <asp:TextBox ID="txtname" runat="server"></asp:TextBox> 
        <br />
        <asp:Label ID="lbsex" runat="server" Text="性别"></asp:Label>
        <asp:DropDownList ID="ddlsex" runat="server">
            <asp:ListItem Selected="True" Value="1">男</asp:ListItem>
            <asp:ListItem Value="0">女</asp:ListItem>
        </asp:DropDownList><br />
        <asp:Label ID="lbcompany" runat="server" Text="公司"></asp:Label>
        <asp:TextBox ID="txtcompany" runat="server"></asp:TextBox><br />
                
        <asp:Button ID="btnsave" runat="server" Text="保存" OnClick="btnsave_Click" /></div>
    </form>
</body>
</html>



后台代码

using System;
using System.Data;
using System.Data.SqlClient;
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;

public partial class _Default : System.Web.UI.Page 
{
    db mydb = new db();
    data mydata = new data();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            databind();
        }
    }
    public void databind()
    {
        GridView1.DataSource = mydb.getData();
        GridView1.DataBind();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        databind();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        databind();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        mydata.id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
        mydb.delData(mydata);
        databind();
    }
    protected void btnsave_Click(object sender, EventArgs e)
    {
        mydata.name = txtname.Text;
        mydata.sex = ddlsex.SelectedValue;
        mydata.company = txtcompany.Text;
        mydb.addData(mydata);
        databind();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if(((DropDownList)e.Row.FindControl("ddlsex"))!=null )
        {
            DropDownList ddlsex = (DropDownList)e.Row.FindControl("ddlsex");
            ddlsex.Items.Clear();
            ddlsex.Items.Add(new ListItem("男","1"));
            ddlsex.Items.Add(new ListItem("女","0"));
            ddlsex.SelectedValue = ((HiddenField)e.Row.FindControl("hdfsex")).Value ;
        }
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        mydata.id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
        mydata.name = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("txtname"))).Text;
        mydata.sex = ((DropDownList)(GridView1.Rows[e.RowIndex].FindControl("ddlsex"))).SelectedValue;
        mydata.company = ((TextBox )(GridView1.Rows[e.RowIndex].FindControl("txtcompany"))).Text ;
        mydb.upData(mydata );
        GridView1.EditIndex = -1;
        databind();
    }

}



--------------------编程问答-------------------- 数据操作类db.cs

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;

/// <summary>
/// Summary description for db
/// </summary>
public class db
{
    string strCn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
public db()
{
//
// TODO: Add constructor logic here
//
}
    public DataTable getData()
    {
        DataTable dt = new DataTable();
        SqlDataAdapter sqlAda = new SqlDataAdapter("getData",strCn);
        sqlAda.Fill(dt);
        return dt;
    }
    public void delData(data mydata)
    {
        SqlConnection sqlCn = new SqlConnection(strCn);
        SqlCommand sqlCmd = new SqlCommand("delData", sqlCn);
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Parameters.Add("@id", SqlDbType.Int, 4);
        sqlCmd.Parameters["@id"].Value = mydata.id;
        try
        {
            sqlCn.Open();
            sqlCmd.ExecuteNonQuery();
            sqlCn.Close();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        { 
        }
    }
    public void addData(data mydata)
    {
        SqlConnection sqlCn = new SqlConnection(strCn);
        SqlCommand sqlCmd = new SqlCommand("addData", sqlCn);
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Parameters.Add("@name", SqlDbType.VarChar,50);
        sqlCmd.Parameters.Add("@sex", SqlDbType.Char, 1);
        sqlCmd.Parameters.Add("@company",SqlDbType.VarChar,50);
        sqlCmd.Parameters["@name"].Value = mydata.name;
        sqlCmd.Parameters["@sex"].Value = mydata.sex;
        sqlCmd.Parameters["@company"].Value = mydata.company;
        try
        {
            sqlCn.Open();
            sqlCmd.ExecuteNonQuery();
            sqlCn.Close();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally 
        {
        }
    }
    public void upData(data mydata)
    {
        SqlConnection sqlCn = new SqlConnection(strCn);
        SqlCommand sqlCmd = new SqlCommand("updateData", sqlCn);
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Parameters.Add("@id",SqlDbType.Int,4);
        sqlCmd.Parameters.Add("@name", SqlDbType.VarChar, 50);
        sqlCmd.Parameters.Add("@sex", SqlDbType.Char, 1);
        sqlCmd.Parameters.Add("@company", SqlDbType.VarChar, 50);
        sqlCmd.Parameters["@id"].Value = mydata.id;
        sqlCmd.Parameters["@name"].Value = mydata.name;
        sqlCmd.Parameters["@sex"].Value = mydata.sex;
        sqlCmd.Parameters["@company"].Value = mydata.company;
        try
        {
            sqlCn.Open();
            sqlCmd.ExecuteNonQuery();
            sqlCn.Close();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
        }
    }
}


实体类data.cs


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;

/// <summary>
/// Summary description for data
/// </summary>
public class data
{
    public data()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    private int _id;
    private string _name = string.Empty;
    private string _sex = string.Empty;
    private string _company = string.Empty;
    public int id
    {
        set { _id = value; }
        get { return _id; }
    }
    public string name
    {
        set { _name = value; }
        get { return _name; }
    }
    public string sex
    {
        set { _sex = value; }
        get { return _sex; }
    }
    public string company
    {
        set { _company = value; }
        get { return _company; }
    }
}

--------------------编程问答-------------------- 将盗墓进行到底 --------------------编程问答--------------------
引用 15 楼 li_1042237864 的回复:
将盗墓进行到底

衰人,N多年前的贴子也往外挖。 --------------------编程问答-------------------- 绑定!
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,