C# 如何从代码隐藏绑定GridView并更新它

C# 如何从代码隐藏绑定GridView并更新它,c#,asp.net,gridview,C#,Asp.net,Gridview,我检查了很多网站,参考了很多代码,然后才可以在这里发布问题。看到他们,我感到很困惑。这是我的问题 我有一个GridView,我将它从代码背后绑定为: public void BindData() { SqlCommand comd = new SqlCommand("SELECT * FROM " + Label2.Text + "", con); SqlDataAdapter da = new SqlDataAdapter(comd); DataTable dt = n

我检查了很多网站,参考了很多代码,然后才可以在这里发布问题。看到他们,我感到很困惑。这是我的问题

我有一个
GridView
,我将它从代码背后绑定为:

public void BindData()
{
    SqlCommand comd = new SqlCommand("SELECT * FROM " + Label2.Text + "", con);
    SqlDataAdapter da = new SqlDataAdapter(comd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    GridView2.DataSource = dt;
    GridView2.DataBind();
}
与我的asp.net相同,如下所示:

<asp:GridView ID="GridView1" runat="server" ForeColor="#333333" 
                AutoGenerateEditButton="True" DataKeyNames="Locations" 
                onrowcancelingedit="GridView1_RowCancelingEdit" 
                onrowdatabound="GridView1_RowDataBound" 
                onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

    <Columns>
        <asp:TemplateField HeaderText="Locations">
            <ItemTemplate>
                <asp:Label ID="LblLocations" runat="server" Text='<%#Eval("Locations") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Lamp_Profile1">
            <ItemTemplate>
                <asp:Label ID="LblLamp_Profile1" runat="server" Text='<%#Eval("Lamp_Profile1") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Label ID="LblEditLamp_Profile1" runat="server" Text='<%#Eval("Lamp_Profile1") %>'></asp:Label>
            </EditItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Fan_Profile1">
            <ItemTemplate>
                <asp:Label ID="LblFan_Profile1" runat="server" Text='<%#Eval("Fan_Profile1") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Label ID="LblEditFan_Profile1" runat="server" Text='<%#Eval("Fan_Profile1") %>'></asp:Label>
            </EditItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="AC_Profile1">
            <ItemTemplate>
                <asp:Label ID="LblAC_Profile1" runat="server" Text='<%#Eval("AC_Profile1") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Label ID="LblEditAC_Profile1" runat="server" Text='<%#Eval("AC_Profile1") %>'></asp:Label>
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>

    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <EditRowStyle BackColor="#999999" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
而我的
GridView1\u行编辑
如下所示:

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridView1.EditIndex = e.RowIndex;

    Label Locations = GridView1.Rows[e.RowIndex].FindControl("LblLocations") as Label;
    //ViewState["Locations_Instance"] = Locations.Text;

    Label Lamp_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblLamp_Profile1") as Label;
    Label Fan_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblFan_Profile1") as Label;
    Label AC_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblAC_Profile1") as Label;

    string query = "UPDATE " + Label3.Text + " SET Lamp_Profile1 ='" + Lamp_Profile1 + "', Fan_Profile1 ='" + Fan_Profile1 + "', AC_Profile1 ='" + AC_Profile1 + "' WHERE Locations = '" + Locations + "'";
    com = new SqlCommand(query, con);
    con.Open();
    com.ExecuteNonQuery();
    con.Close();
    GridView1.EditIndex = -1;

    BindData();
    //lbldisplay.Text = "Updated Successfully";
}
我的
GridView1\u行更新
如下所示:

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridView1.EditIndex = e.RowIndex;

    Label Locations = GridView1.Rows[e.RowIndex].FindControl("LblLocations") as Label;
    //ViewState["Locations_Instance"] = Locations.Text;

    Label Lamp_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblLamp_Profile1") as Label;
    Label Fan_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblFan_Profile1") as Label;
    Label AC_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblAC_Profile1") as Label;

    string query = "UPDATE " + Label3.Text + " SET Lamp_Profile1 ='" + Lamp_Profile1 + "', Fan_Profile1 ='" + Fan_Profile1 + "', AC_Profile1 ='" + AC_Profile1 + "' WHERE Locations = '" + Locations + "'";
    com = new SqlCommand(query, con);
    con.Open();
    com.ExecuteNonQuery();
    con.Close();
    GridView1.EditIndex = -1;

    BindData();
    //lbldisplay.Text = "Updated Successfully";
}
从中,我得到了使用模板字段以及
GridView
中的数据库列绑定的所有行,一旦我在
GridView
中单击编辑,整个
GridView
就会消失。


请帮助我。

您可以在下面的行更新事件中找到编辑事件生成的文本框,并将其分配给字符串变量

然后使用一个单独的函数更新输入的值,最后调用BindGrid()函数,该函数将再次绑定gridview

注意:我正在使用存储过程更新我的DB表

protected void grdKeywords_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
       GridViewRow row = (GridViewRow)grdKeywords.Rows[e.RowIndex];
       TextBox txtKeyword = row.FindControl("txtGridKeyword") as TextBox;
       string keyword = string.Empty;
       keyword = txtKeyword.Text;
       UpdateKeyword(keyword.ToLower());

    }



public int UpdateKeyword(string strKeyword)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
        SqlCommand cmdUpdateKeyword = BuildCommand(conn, "proc_UpdateKeyword");
        cmdUpdateKeyword.Parameters.AddWithValue("@Keyword", strKeyword);
        conn.Open();
        int i = Convert.ToInt32(cmdUpdateKeyword.ExecuteScalar());
        conn.Close();
        BindGrid();

    }

要手动为gridview指定列,必须设置AutoGenerateColumns=“false”
。现在可以在GridView中指定所需的列。现在可以同时使用“BoundFields”和“TemplateFields”。如下图所示

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
        <Columns>
            <asp:BoundField DataField="column1" HeaderText="Column1" SortExpression="" />
          <asp:BoundField DataField="column2" HeaderText="Column2" SortExpression="" />
            <asp:TemplateField SortExpression="points">
            <HeaderTemplate>HELLO</HeaderTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("hello") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

如果在页面加载中调用BindData,请执行以下操作:

if (!IsPostBack)
    BindData();
这可能会解决你的问题


干杯

确保在GridView中设置了EnableViewState=“true”。它解决了我的失踪问题。

试试这个

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

    GridView1.EditIndex = e.RowIndex;
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];


    TextBox PrStyle = (TextBox)row.FindControl("PrStyle");
    TextBox PrID = (TextBox)row.FindControl("PrID");

    GridView1.EditIndex = -1;


    SqlCommand cmd = new SqlCommand("Update dt Set PrStyle='" + PrStyle + "',PrID='" + PrID + "'");
}

您遇到了什么问题或错误?由于我正在从
Label2
绑定
GridView
,在生成
Label2
文本之前,我无法在if(!IsPostBack)中使用。它给了我一个错误,无效的
Label2
只有在我使用模板字段时才会写入无效的GridView1\u行数据绑定(对象发送方,GridViewRowEventArgs e…?您能解释一下您的代码吗?只有代码的答案被认为质量很低(例如,请参阅)
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

    GridView1.EditIndex = e.RowIndex;
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];


    TextBox PrStyle = (TextBox)row.FindControl("PrStyle");
    TextBox PrID = (TextBox)row.FindControl("PrID");

    GridView1.EditIndex = -1;


    SqlCommand cmd = new SqlCommand("Update dt Set PrStyle='" + PrStyle + "',PrID='" + PrID + "'");
}