简体   繁体   中英

How to maintain textbox state after postback if it is inside a TemplateField?

I have an aspx page that contains an <asp:Gridview> and displays data from a database.

On the header of the Gridview , I placed a TextBox on each column that can be used to search data from Gridview after pressing Enter. So after hitting enter, it will rebind the gridview, then the searched data will be displayed. Works fine but the text inserted on textbox disappears.

I don't want the text to disappear after rebinding the gridview. So that 'the user can continue on inserting text on the other textbox, and the gridview can display a more specific data.'

Is this possible? or is there any alternatives to achieve my goal?

EDIT

Here's my code:

Page_Load

SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString);

protected void Page_Load(object sender, EventArgs e)
{

    if (!Page.IsPostBack)
    {
        PopulateData();
        onSearch();
    }        
}

Search Event On_Click

protected void btnFilter_Click(object sender, EventArgs e)
{
    TextBox tbDelegate = (TextBox)TraineeGrid.HeaderRow.Cells[3].FindControl("newDelegate");
    TextBox tbRankPos = (TextBox)TraineeGrid.HeaderRow.Cells[4].FindControl("newRankPos");
    TextBox tbCompany = (TextBox)TraineeGrid.HeaderRow.Cells[5].FindControl("newCompany");
    TextBox tbCourse = (TextBox)TraineeGrid.HeaderRow.Cells[6].FindControl("newCourse");
    TextBox tbCenter = (TextBox)TraineeGrid.HeaderRow.Cells[7].FindControl("newCenter");
    TextBox tbInstructor = (TextBox)TraineeGrid.HeaderRow.Cells[8].FindControl("newInstructor");
    TextBox tbSdate = (TextBox)TraineeGrid.HeaderRow.Cells[9].FindControl("newStartDate");
    TextBox tbEdate = (TextBox)TraineeGrid.HeaderRow.Cells[10].FindControl("newEndDate");
    DropDownList tbCissued = (DropDownList)TraineeGrid.HeaderRow.Cells[11].FindControl("newCertIssued");
    TextBox tbCnumber = (TextBox)TraineeGrid.HeaderRow.Cells[12].FindControl("newCertNumber");
    TextBox tbRemark = (TextBox)TraineeGrid.HeaderRow.Cells[13].FindControl("newRemark");


    DataTable dt = new DataTable();

    using (con)
    {
        string sql = "select ID, Delegate, RankPos, Company, CourseTitle, "+
                     "TrainingCenter, Instructor, convert(varchar(10), " +
                     "StartDate, 101) as [StartDate], convert(varchar(10), "+
                     "EndDate, 101) as [EndDate], CertIssued, CertNumber, "+
                     "Remarks from Trainees ";

        if (tbDelegate.Text != string.Empty)
        {
            HasWhereClause = true;
            sql+= "where Delegate LIKE '%" + tbDelegate.Text + "%'";
        }

        if (tbRankPos.Text != string.Empty)
        {
            if (HasWhereClause)
            {
                sql += "and RankPos LIKE '%" + tbRankPos.Text + "%'";
            }
            else
            {
                HasWhereClause = true;
                sql += "where RankPos LIKE '%" + tbRankPos.Text + "%'";
            }               
        }

        if (tbCompany.Text != string.Empty)
        {
            if (HasWhereClause)
            {
                sql += "and Company LIKE '%" + tbCompany.Text + "%'";
            }
            else
            {
                HasWhereClause = true;
                sql += "where Company LIKE '%" + tbCompany.Text + "%'";
            }
        }

        if (tbCourse.Text != string.Empty)
        {
            if (HasWhereClause)
            {
                sql += "and CourseTitle LIKE '%" + tbCourse.Text + "%'";
            }
            else
            {
                HasWhereClause = true;
                sql += "where CourseTitle LIKE '%" + tbCourse.Text + "%'";
            }
        }

        if (tbCenter.Text != String.Empty)
        {
            if (HasWhereClause)
            {
                sql += "and TrainingCenter LIKE'%" + tbCenter.Text + "%'";
            }
            else
            {
                HasWhereClause = true;
                sql += "where TrainingCenter LIKE'%" + tbCenter.Text + "%'";
            }
        }

        if (tbInstructor.Text != String.Empty)
        {
            if (HasWhereClause)
            {
                sql += "and Instructor LIKE '%" + tbInstructor.Text + "%'";
            }
            else
            {
                HasWhereClause = true;
                sql += "where Instructor LIKE '%" + tbInstructor.Text + "%'";
            }
        }

        if (tbSdate.Text != String.Empty)
        {
            if (HasWhereClause)
            {
                sql += "and StartDate LIKE '%" + tbSdate.Text + "%'";
            }
            else
            {
                HasWhereClause = true;
                sql += "where StartDate LIKE '%" + tbSdate.Text + "%'";
            }
        }

        if (tbEdate.Text != String.Empty)
        {
            if (HasWhereClause)
            {
                sql += "and EndDate LIKE '%" + tbEdate.Text + "%'";
            }
            else
            {
                HasWhereClause = true;
                sql += "where EndDate LIKE '%" + tbEdate.Text + "%'";
            }
        }

        if (tbCissued.SelectedIndex != 0)
        {
            if (HasWhereClause)
            {
                sql += "and CertIssued LIKE '%" + tbCissued.SelectedValue + "%'";
            }
            else
            {
                HasWhereClause = true;
                sql += "where CertIssued LIKE '%" + tbCissued.SelectedValue + "%'";
            }
        }

        if (tbRemark.Text != String.Empty)
        {
            if (HasWhereClause)
            {
                sql += "and Remarks LIKE '%" + tbCissued.Text + "%'";
            }
            else
            {
                HasWhereClause = true;
                sql += "where Remarks LIKE '%" + tbCissued.Text + "%'";
            }
        }
        using (SqlCommand cmd = new SqlCommand(sql, con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                da.Fill(dt);
            }
        }
    }
        if (dt.Rows.Count > 0)
        {
            TraineeGrid.DataSource = dt;
            TraineeGrid.DataBind();
        }
        else if (dt.Rows.Count == 0)
        {
            dt.Rows.Add(dt.NewRow());
            TraineeGrid.DataSource = dt;
            TraineeGrid.DataBind();
            TraineeGrid.Rows[0].Cells.Clear();
            TraineeGrid.Rows[0].Cells.Add(new TableCell());
            TraineeGrid.Rows[0].Cells[0].ColumnSpan = dt.Columns.Count;
            TraineeGrid.Rows[0].Cells[0].Text = "No Data Found";
            TraineeGrid.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
        }
}

DataBind Function

private void PopulateData()
{

    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
    {
        string sql = "select ID, Delegate, RankPos, Company, CourseTitle, TrainingCenter, Instructor, convert(varchar(10), " +
            "StartDate, 101) as [StartDate], convert(varchar(10), EndDate, 101) as [EndDate], CertIssued, CertNumber, Remarks " +
            "from Trainees Order By ID Asc";


        using (SqlCommand cmd = new SqlCommand(sql, con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                da.Fill(dt);
            }
        }
   }

    if (dt.Rows.Count > 0)
    {            
        TraineeGrid.DataSource = dt;            
        TraineeGrid.DataBind();
    }

    else
    {
        dt.Rows.Add(dt.NewRow());
        TraineeGrid.DataSource = dt;
        TraineeGrid.DataBind();
        TraineeGrid.Rows[0].Cells.Clear();
        TraineeGrid.Rows[0].Cells.Add(new TableCell());
        TraineeGrid.Rows[0].Cells[0].ColumnSpan = dt.Columns.Count;
        TraineeGrid.Rows[0].Cells[0].Text = "No Data Found";
        TraineeGrid.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
    }
}

OnSearch Function

private void onSearch()
{
    Button btnFilter = (Button)TraineeGrid.HeaderRow.Cells[2].FindControl("gvFilter");
    TextBox tbDelegate = (TextBox)TraineeGrid.HeaderRow.Cells[3].FindControl("newDelegate");
    TextBox tbRankPos = (TextBox)TraineeGrid.HeaderRow.Cells[4].FindControl("newRankPos");
    TextBox tbCompany = (TextBox)TraineeGrid.HeaderRow.Cells[5].FindControl("newCompany");
    TextBox tbCourse = (TextBox)TraineeGrid.HeaderRow.Cells[6].FindControl("newCourse");
    TextBox tbCenter = (TextBox)TraineeGrid.HeaderRow.Cells[7].FindControl("newCenter");
    TextBox tbInstructor = (TextBox)TraineeGrid.HeaderRow.Cells[8].FindControl("newInstructor");
    TextBox tbSdate = (TextBox)TraineeGrid.HeaderRow.Cells[9].FindControl("newStartDate");
    TextBox tbEdate = (TextBox)TraineeGrid.HeaderRow.Cells[10].FindControl("newEndDate");
    DropDownList tbCissued = (DropDownList)TraineeGrid.HeaderRow.Cells[11].FindControl("newCertIssued");
    TextBox tbCnumber = (TextBox)TraineeGrid.HeaderRow.Cells[12].FindControl("newCertNumber");
    TextBox tbRemark = (TextBox)TraineeGrid.HeaderRow.Cells[13].FindControl("newRemark");

    tbDelegate.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
    tbRankPos.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
    tbCompany.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
    tbCourse.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
    tbCenter.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
    tbInstructor.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
    tbSdate.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
    tbEdate.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
    tbCissued.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
    tbCnumber.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
    tbRemark.Attributes.Add("OnKeyPress", "return controlEnter('" + btnFilter.ClientID + "',event)");
}

On your search button click:

    protected void btnSearch_Click(object sender, EventArgs e)
        {
//this code should be executed before any other code to ensure it is executed.
            ViewState["Values"] += TextBox1.Text;
        }

On your gridview row data bound method ( http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx ):

  protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
  {

    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        TextBox t = (TextBox) e.Row.FindControl("TextBox1");
        t.Text = ViewState["Values"].ToString();   
    }   
  }

Please read up on how to create a rowdatabound method if it doesn't exist

You need to do this to populate the values on the Updating event This to populate the NewValues with the data.

GridView gv = (GridView)sender;
 for (int i = 0; i < GridViewInput.Columns.Count; i++)
 {
  DataControlFieldCell cell = gv.Rows[e.RowIndex].Cells[i] as 
  DataControlFieldCell;
  gv.Columns[i].ExtractValuesFromCell(e.NewValues, cell, 
   DataControlRowState.Edit, true);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM