C# 如何从后面的代码绑定 GridView 并更新相同的代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12275940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:43:17  来源:igfitidea点击:

How to bind a GridView from code behind and update the same

c#asp.netgridview

提问by Archana B.R

I check many sites and referred many codes before I could post a questions here. I am facing lot of confusions seeing them. Here is my problem.

在我在这里发布问题之前,我检查了许多网站并参考了许多代码。看到他们,我面临很多困惑。这是我的问题。

I have a GridViewand I have bound it from code behind as :

我有一个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();
}

And my asp.net for the same looks like :

和我的 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>

And I have written my GridView1_RowCancelingEditlike:

我写了我的GridView1_RowCancelingEdit喜欢:

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    e.Cancel = true;
    GridView1.EditIndex = -1;
}

And my GridView1_RowEditinglooks like:

我的GridView1_RowEditing样子:

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

And my GridView1_RowUpdatinglooks like:

我的GridView1_RowUpdating样子:

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";
}

From this I am getting what ever row I am binding using template field as well as database columns in my GridViewand Once I click on Edit in the GridView, the whole GridViewdisappears.

从这里我得到了我使用模板字段和数据库列绑定的任何行GridView,一旦我点击编辑GridView,整个GridView消失。

Please help me.

请帮我。

回答by Amin Sayed

You can find the textbox that is generated on edit event in the RowUpdatingevent below and assign it to a string variable.

您可以在下面的RowUpdating事件中找到在编辑事件上生成的文本框,并将其分配给一个字符串变量。

Then have a seperate function to update the values entered and finally call your BindGrid() function which again binds the gridview..

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

Note: I'm using stored procedure to update my DB table.

注意:我正在使用存储过程来更新我的数据库表。

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();

    }

回答by Kapil Khandelwal

To manually specify columns for the gridview you have to set AutoGenerateColumns="false". Now you can specify the columns that you want in your GridView. You can use both "BoundFields" & "TemplateFields" now. As shown below.

要为 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>

Now you can use:

现在您可以使用:

GridView.RowDataBound Eventto bind data to the data row.

GridView.RowDataBound将数据绑定到数据行的事件

 void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
  {

    if(e.Row.RowType == DataControlRowType.DataRow)
    {

      Label Label1= ((Label)e.Row.FindControl("Label1"));
      Label1.Text = "YOURDATA";

    }

  }

回答by Ran

if you call BindData in page load then do that:

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

if (!IsPostBack)
    BindData();

That might solve your problem...

那可能会解决您的问题...

Cheers

干杯

回答by Raja

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();

}

回答by RonVibbentrop

Make sure you have EnableViewState="true" set in your GridView. It solved disapperance-issue in my case.

确保您在 GridView 中设置了 EnableViewState="true"。在我的情况下,它解决了消失问题。

回答by vishwa ratna

try this ..

尝试这个 ..

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 + "'");
}