Saira
Saira

Reputation: 123

How can insert values into gridview rows ? ASP.NET ,C#

My question is how can i insert values into gridviews rows.Basically I have created a gridview in which i bound the footer and i want to insert values in the footer.I have create a 'textboxs','dropdownlist' and 'checkboxes'.I want when i insert value and press "Insert" button then values shown in the gridview and again i insert value and press button then show inserted values in the gridview.Here is my gridview image image

and i also want to edit and delete rows as well.Here is my code : aspx code

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        Height="104px" ShowFooter="True" Width="463px" 
        AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
        <Columns>
            <asp:TemplateField HeaderText="Column Name">
            <FooterTemplate>
             <asp:TextBox ID="name" runat="server"></asp:TextBox>
             </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Data Type">
            <FooterTemplate>
                <asp:DropDownList ID="DropDownList2" runat="server">
                </asp:DropDownList>
             </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Allow Null">
            <FooterTemplate>
                <asp:CheckBox ID="allow_null" runat="server" />
            </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Primary Key">
            <FooterTemplate>
                <asp:CheckBox ID="primary" runat="server" />
            </FooterTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

and here is my aspx.cs code :

protected void Button1_Click(object sender, EventArgs e)
{
    string name = TextBox1.Text;
    string type = DropDownList1.Text;
    string allow=Null.Text;
    string primary = Primary.Text;
    name = ((TextBox)GridView1.FooterRow.FindControl("TextBox2")).Text;
    type = ((DropDownList)GridView1.FooterRow.FindControl("DropDownList2")).Text;
    allow = ((CheckBox)GridView1.FooterRow.FindControl("allow_null")).Text;
    primary = ((CheckBox)GridView1.FooterRow.FindControl("primary")).Text; 
}

Upvotes: 1

Views: 9393

Answers (2)

fnostro
fnostro

Reputation: 4591

To use the GridView in this way, with input fields in the footer and a Insert Button that is outside the GridView, you need to make a manual Insert.

I don't know how you perform an Insert using the EF model as I don't currently use it. I guess you could say the "old" way is to use an instance of SqlConnection and SqlCommand. You would use code similar to this inside your Button Click event:

// This is VB.  C# is similar, you will have to convert where needed

Using connection As New SqlConnection(connectionString)
  Using command As New SqlCommand(queryString, connection)
    command.Connection.Open()

    command.CommandType = // Typically Text or StoredProcedure as needed
    command.Parameters.AddWithValue("@parameter_name1", some_value_1)
    command.Parameters.AddWithValue("@parameter_name2", some_value_2)
    .
    .
    .
    command.ExecuteNonQuery()
  End Using
End Using

queryString is your sql INSERT statement or a stored procedure

command.Parameters is a collection of replaceable parameter in your INSERT statement or Stored Proc.


Addendum

A Gridview is a Data bound control so typically when you use a gridview it's bound to some backing data source. If you are not using a database then you are using some other construct.

If you are using, for example, a DataTable, you would add the new rows and columns to the DataTable using its row and column methods and then rebind the DataTable to the Gridview. You don't add rows and columns directly to a GridView.

See this other SO answer by JonH for an example

Upvotes: 4

Sam Hobbs
Sam Hobbs

Reputation: 2881

In case this helps this is based on the ASPSnippets but modified to be more like you might need. Note that instead of using a DataTable I am using a List where "Row" is a class. It is somewhat a matter of personal preference which one you use. The "Row" class is:

[Serializable]
public class Row
{
    public string FieldName { get; set; }
    public string FieldType { get; set; }
    public Boolean FieldNullible { get; set; }
    public Boolean FieldPrimaryKey { get; set; }
}

My names are different from your names. Note that the ASPSnippets sample does not use TemplateFields so I am not. I am not sure if you need to make the "allow" and/or "primary" fields Boolean so I did not process them in the form. So the ASP.Net form I have is:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    Height="104px" Width="463px"
    AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
    <Columns>
        <asp:BoundField DataField="FieldName" HeaderText="Name" ItemStyle-Width="120" />
        <asp:BoundField DataField="FieldType" HeaderText="Type" ItemStyle-Width="120" />
    </Columns>
</asp:GridView>
<br /><asp:Label ID="Label1" runat="server" Text="Name:"></asp:Label>
<br /><asp:TextBox ID="txtName" runat="server" />
<br /><asp:Label ID="Label2" runat="server" Text="Type:"></asp:Label>
<br /><asp:TextBox ID="txtType" runat="server" />
<br /><asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />

The code-behind is:

protected void Page_Load(object sender, EventArgs e)
{
    if (this.IsPostBack)
        return;
    List<Row> Rows = new List<Row>();
    ViewState["Rows"] = Rows;
    BindGrid();
}

protected void BindGrid()
{
    GridView1.DataSource = (List<Row>)ViewState["Rows"];
    GridView1.DataBind();
}

protected void Insert(object sender, EventArgs e)
    {
        List<Row> Rows = (List < Row >)ViewState["Rows"];
        Row r = new Row();
        r.FieldName = txtName.Text.Trim();
        r.FieldType = txtType.Text.Trim();
        Rows.Add(r);
        ViewState["Rows"] = Rows;
        BindGrid();
        txtName.Text = string.Empty;
        txtType.Text = string.Empty;
}

One thing I do not like is that the GridView does not show until there is data in it. I assume you can fix that.

This does not implement the editing and deleting.

Upvotes: 0

Related Questions