Syed Sohail Ahmed
Syed Sohail Ahmed

Reputation: 45

Add rows to asp:gridview - taking values from text boxes

I want to add the values entered in textboxes to a gridview on the same page. I am using a button and Event(btn_add_Click) to do this.

I used an IF loop to check the old data of the gridview and I try to maintain it in List.

When I enter data in the text boxes - The row gets added the first time. But second time - when the Session["dt"] carries data, it enters the IF loop erroring at the typecast of the session variable.

Please suggest as how to type cast the session - or how to maintain the old data of the gridview when adding a new row.

Code--

protected void btn_add_Click(object sender, EventArgs e)
    {
        List<Member> lstMember = new List<Member>();
        if (Session["dt"] != null)
        {
            lstMember = (List<Member>)Session["dt"];
        }
        Member Member = new Member();

    Member.Name = txt_NameMember.Text;
    Member.Mobile = txt_MobileMem.Text;
    Member.Email = txt_EmailMem.Text;
    Member.Degree = txt_degreeMem.Text;
    Member.Nationality = txt_NatMem.Text;
    Member.Skills = txt_SkillsMem.Text;
    lstMember.Add(new Member(Member));
    gv_memDetails.DataSource = lstMember;
    gv_memDetails.DataBind();
    Session["dt"] = lstMember;
}

public class Member
{
    public Member() { }
    public Member(Member cust)
    {

        Name = cust.Name;
        Mobile = cust.Mobile;
        Email = cust.Email;
        Degree = cust.Degree;
        Nationality = cust.Nationality;
        Skills = cust.Skills;
    }
    public string Name { get; set; }
    public string Mobile { get; set; }
    public string Email { get; set; }
    public string Degree { get; set; }
    public string Nationality { get; set; }
    public string Skills { get; set; }

}

I checked this link - it has the same typecast. But errors out in my code.

Add new row data to gridview asp.net c#


_MY GOAL IS TO ADD A ROW TO GRIDVIEW BY TAKING VALUES FROM TEXTBOXES... PLEASE SUGGEST ANYWAY.... MAY BE A NEW ONE...

Upvotes: 0

Views: 759

Answers (2)

Samiey Mehdi
Samiey Mehdi

Reputation: 9424

put [Serializable] before class name:

[Serializable]
public class Member
{ ... }

then replace

Session["dt"]

with

ViewState["dt"]

Upvotes: 1

serene
serene

Reputation: 685

What is the error that you are getting? Make sure you are not resetting the session in postback. Try checking if your session is the list of your class: Like:

var data=Session["dt"];
if(data is List<Member>)
{
//your code here
}

Upvotes: 0

Related Questions