1

I have 1 Dropdownlist and 3 Textboxes and I want to add data from textboxes and after a button click they will be added to GridView

<asp:DropdownList ID="ddlClassification" runat="server" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>Sample 1</asp:ListItem>
<asp:ListItem>Sample 2</asp:ListItem>
<asp:ListItem>Sample 3</asp:ListItem>
</asp:DropdownList>

<asp:TextBox ID="tbCost" runat="server" Width="100" ></asp:TextBox>
<asp:TextBox ID="tbAccumulate" runat="server" Width="100" ></asp:TextBox>
<asp:TextBox ID="tbNRV" runat="server" Width="100" ></asp:TextBox>

<asp:Button ID="btnAdd" runat="server" Text="ADD" onclick="btnAdd_Click" />

and this is What I have in code behind

public partial class SetUP : System.Web.UI.Page
{
    DataRow dr;
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        dt.Columns.Add("Classification");
        dt.Columns.Add("Cost");
        dt.Columns.Add("Accumulate");
        dt.Columns.Add("NRV");
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        dr = dt.NewRow();
        dr["Classification"] = ddlClassification.Text;
        dr["Cost"] = tbCost.Text;
        dr["Accumulate"] = tbAccumulate.Text;
        dr["NRV"] = tbNRV.Text;
        dt.Rows.Add(dr);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

I have done this once but now I am getting error on GridView1.DataBind(); can someone help me in my problem

4
  • what's the error you get? Commented Mar 8, 2014 at 1:18
  • Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition. GridView1.DataBind(); Commented Mar 8, 2014 at 1:20
  • I feel like your gridview will get cleared out anyways because in your page load you are adding the columns on every post back. You should include if(!isPostBack){ //add columns } t Commented Mar 8, 2014 at 1:26
  • @MatthewWong now I'm getting error on dr["Classification"] = ddlClassification.Text; Commented Mar 8, 2014 at 1:33

1 Answer 1

1

when you add column do like this

 dt.Columns.Add(new DataColumn("Classification", typeof(string)));

should help you

Sign up to request clarification or add additional context in comments.

6 Comments

what about in page_load ?
its working now one more question when I enter value and clicks the button it will add the data I entered and when I add another data it removes the old one and change the new data i entered
Oh so you want to keep on adding! if so, Matthew's suggestion should fix that issue
yea just add the if (!isPostBack) logic
if (!isPostBack) in click ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.