Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Every One,
i am developing one web site in that columns are dynamic by the templates fields.
my problem is on postback my gridview become blank.
pl help me to resolve this.

here is code
ASP.NET
<pre lang="xml"><%@ Page Title="" Language="C#" MasterPageFile="~/HOSPITAL/MasterHospital.master"
    AutoEventWireup="true" CodeFile="ImeiDetails.aspx.cs" Inherits="HOSPITAL_ImeiDetails"
    Theme="SkinFile" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div>
        <p class="infopost">
            Imei Details
        </p>
        <div>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <div>
                        <table class="style1">
                            <tr>
                                <td class="leftcol">
                                    Select Type
                                </td>
                                <td class="leftmidd">
                                    :
                                </td>
                                <td>
                                    <asp:DropDownList ID="DropDownList1" runat="server">
                                        <asp:ListItem Value="nDoctorLimit">Doctors</asp:ListItem>
                                        <asp:ListItem Value="nChemistLimit">Chemist</asp:ListItem>
                                        <asp:ListItem>Lab</asp:ListItem>
                                    </asp:DropDownList>
                                </td>
                                <td>
                                    <asp:Button ID="BtnLoadClick" runat="server" Text="Load" OnClick="BtnLoadClick_Click" />
                                </td>
                                <td>
                                    <asp:Button ID="BtnUpdate" runat="server" Text="Update"
                                        onclick="BtnUpdate_Click" />
                                </td>
                                <td>
                                    <asp:UpdateProgress ID="UpdateProgress" runat="server" AssociatedUpdatePanelID="UpdatePanel1"
                                        DisplayAfter="0" DynamicLayout="false">
                                        <ProgressTemplate>
                                        Pl Wait ...
                                            <asp:Image ID="Image1" runat="server" Height="10px"
                                                ImageUrl="~/images/progress.gif" Width="100px" />

                                        </ProgressTemplate>
                                    </asp:UpdateProgress>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div>
                        <asp:Panel ID="Panel2" runat="server">
                        </asp:Panel>
                    </div>
                    <div>
                        <asp:Panel ID="Panel1" runat="server" Height="500px" ScrollBars="Both"
                            Width="700px">
                            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EmptyDataText="No Data Available">
                            </asp:GridView>
                        </asp:Panel>
                    </div>
                    <div>
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </div>
</asp:Content>



C# Code
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class HOSPITAL_ImeiDetails : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    string Field;
    string JoinCondition; string tablename; string RecurringField;
    protected void BtnLoadClick_Click(object sender, EventArgs e)
    {
        if (true)
        {

        }
        DataSet DsLimit = ClassHospital.GetDataSet("select nImeiNoLimit from hospitalmaster where nhospitalid=" + Session["Hospital_Id"].ToString());
        if (DsLimit.Tables[0].Rows.Count > 0)
        {
            double Limit = Convert.ToDouble(DsLimit.Tables[0].Rows[0][0].ToString());

            if (DropDownList1.SelectedIndex == 0)
            {
                tablename = "DoctorMaster";
                Field = " DoctorMaster.nDoctorId as [Doctor_Id],DoctorMaster.cDoctorName AS [Doctor_Name],ImeiDetails.cImeiNo as [Imei],";
                JoinCondition = " ON DoctorMaster.nHospitalId = HospitalMaster.nHospitalId LEFT OUTER JOIN " +
                         " ImeiDetails ON DoctorMaster.nDoctorId = ImeiDetails.nDoctorId ";
                RecurringField = "nDoctorId";
            }
            else if (DropDownList1.SelectedIndex == 1)
            {
                tablename = "ChemistMaster";
                Field = " ChemistMaster.nChemistId as [Chemist_Id],ChemistMaster.cChemistName AS [Chemist_Name],ImeiDetails.cImeiNo as [Imei],";
                JoinCondition = " ON ChemistMaster.nHospitalId = HospitalMaster.nHospitalId LEFT OUTER JOIN " +
                         " ImeiDetails ON ChemistMaster.nChemistId = ImeiDetails.nChemistId ";
                RecurringField = "nChemistId";
            }
            else if (DropDownList1.SelectedIndex == 2)
            {
                tablename = "LabMaster";
                Field = " LabMaster.nLabId as [Lab_Id],LabMaster.cLabName AS [Lab_Name],ImeiDetails.cImeiNo as [Imei],";
                JoinCondition = " ON LabMaster.nHospitalId = HospitalMaster.nHospitalId LEFT OUTER JOIN " +
                         " ImeiDetails ON LabMaster.nLabId = ImeiDetails.nLabId ";
                RecurringField = "nLabId";
            }

            if (Limit != 0)
            {
                DataLimit(tablename, Field, JoinCondition, Limit, RecurringField);
            }
        }
    }

    public void DataLimit(string TableName, string InitialField, String InitialJoinCondition, double Limit, string RecurringJoinField)
    {
        if (Limit != 0)
        {
            for (int i = 1; i < Limit; i++)
            {
                InitialField += " ImeiDetails_" + i.ToString() + ".cImeiNo  as [Imei_" + i.ToString() + "],";
                InitialJoinCondition += " LEFT OUTER JOIN  ImeiDetails AS ImeiDetails_" + i.ToString() + " ON " + TableName + "." + RecurringField + " = ImeiDetails_" + i.ToString() + "." + RecurringField+ " ";
            }
        }
        if (InitialField.EndsWith(","))
        {
            InitialField = InitialField.Remove(InitialField.Length - 1, 1);
        }
        string FinalQuery = "SELECT " + InitialField + " FROM " + TableName + " INNER JOIN " +
                  " HospitalMaster " + InitialJoinCondition + " where " + TableName + ".nHospitalId=" + Session["Hospital_Id"].ToString();
        DataSet DsFinal = ClassHospital.GetDataSet(FinalQuery);
        DataTable dt = DsFinal.Tables[0];
        int i1 = 0;
        //Iterate through the columns of the datatable to set the data bound field dynamically.
        foreach (DataColumn col in dt.Columns)
        {
            //Declare the bound field and allocate memory for the bound field.
            TemplateField bfield = new TemplateField();

            //Initalize the DataField value.
            bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName, 0, false);
            if (i1 == 0)
            {

                //Initialize the HeaderText field value.
                bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName, 50, false);

            }
            else if (i1 == 1)
            {

                //Initialize the HeaderText field value.
                bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName, 150, false);

            }
            else
            {

                //Initialize the HeaderText field value.
                bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName, 100, true);

            }
            //Add the newly created bound field to the GridView.
            GridView1.Columns.Add(bfield);
            i1++;
        }

        //Initialize the DataSource
        GridView1.DataSource = dt;

        //Bind the datatable with the GridView.
        GridView1.DataBind();
        if (GridView1.Rows.Count>0)
        {
            BtnUpdate.Visible = true;
        }
        else
        {
            BtnUpdate.Visible = false;

        }
    }

    protected void BtnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                for (int j = 0; j < GridView1.Columns.Count; j++)
                {
                    Control c = GridView1.Rows[i].Cells[j].FindControl("tb1") as TextBox;
                }
            }
        }
        catch (Exception)
        {
            
            throw;
        }
    }
}



templete class
C#
<pre lang="c#">
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

//A customized class for displaying the Template Column
public class GridViewTemplate : ITemplate
{
    //A variable to hold the type of ListItemType.
    ListItemType _templateType;

    //A variable to hold the column name.
    string _columnName;

    int _width;
    bool _IsEnabled;
    //Constructor where we define the template type and column name.
    public GridViewTemplate(ListItemType type, string colname,int W,bool E)
    {
        //Stores the template type.
        _templateType = type;

        //Stores the column name.
        _columnName = colname;

        _width = W;
        _IsEnabled = E;

    }

    void ITemplate.InstantiateIn(System.Web.UI.Control container)
    {
        switch (_templateType)
        {
            case ListItemType.Header:
                //Creates a new label control and add it to the container.
                Label lbl = new Label();            //Allocates the new label object.
                lbl.Text = _columnName;             //Assigns the name of the column in the lable.
                container.Controls.Add(lbl);        //Adds the newly created label control to the container.
                break;

            case ListItemType.Item:
                //Creates a new text box control and add it to the container.
                TextBox tb1 = new TextBox();                            //Allocates the new text box object.
                tb1.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.
                tb1.Width=Unit.Pixel(_width);                                   //Creates a column with size 4.
                tb1.Enabled = _IsEnabled;
                if (_IsEnabled==false)
                {
                    tb1.BorderStyle = BorderStyle.None;
                    tb1.Font.Bold = true;
                    tb1.BackColor = Color.White;
                    tb1.ForeColor = Color.Red;
                }
                container.Controls.Add(tb1);                            //Adds the newly created textbox to the container.
                break;

            case ListItemType.EditItem:
                //As, I am not using any EditItem, I didnot added any code here.
                break;

            case ListItemType.Footer:
                CheckBox chkColumn = new CheckBox();
                chkColumn.ID = "Chk" + _columnName;
                container.Controls.Add(chkColumn);
                break;
        }
    }

    /// <summary>
    /// This is the event, which will be raised when the binding happens.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void tb1_DataBinding(object sender, EventArgs e)
    {
        TextBox txtdata = (TextBox)sender;
        GridViewRow container = (GridViewRow)txtdata.NamingContainer;
        object dataValue = DataBinder.Eval(container.DataItem, _columnName);
        if (dataValue != DBNull.Value)
        {
            txtdata.Text = dataValue.ToString();
            txtdata.ToolTip = dataValue.ToString();
        }
    }
}


on btnupdate click my gridview become blank

i also want to retrieve text box value.
pl help
Posted
Updated 30-Jun-14 21:37pm
v2

1 solution

You can follow below steps to resolve the issue:
Step 1: Create a function - LoadData() and move all the code that you've in btnLoadClick_click() event.
Step 2: Call LoadData() from the Load button click event.
Step 3: Call LoadData() from the Update button click event too.

Explanation: Once the page is postback, all the data is lost from the page. You have to bind the data to the GridView control explicitly.
 
Share this answer
 
Comments
Member 8825505 1-Jul-14 13:01pm    
That is true but by doing this way i will lost the values entered in the text box.
how i can resolve that issue .
pl help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900