Pages

Wednesday 22 January 2014

Displaying a table information dynamically ,without using any controls

step1: connect with the database. 


using System.Data.Sqlclient;

sqlconnection conn=new sqlconnection("server=....;user id=...;password=....");


step2: Enter the table name in a textbox,and displaying the table information 

 protected void TextBox1_TextChanged(object sender, EventArgs e)

    {

     try

        {

            string s1 = TextBox1.Text;

            //passing a query to fetch the table from database,which is entered in textbox 

            string s2 = "select * from " + s1;

            SqlDataAdapter da = new SqlDataAdapter(s2, conn);

            da.Fill(ds);

            DataTable dt = new DataTable();

            dt = ds.Tables[0];

           //creating a table dynamically 

            HtmlTable table = new HtmlTable();

            HtmlTableRow tr = null;

            HtmlTableCell tc = null;



           //displaying labels for displaying coloumn names in the table 

            if (dt.Columns.Count - 1 > 0)

            {

                tr = new HtmlTableRow();

                for (int i = 0; i < dt.Columns.Count; i++)

                {

                    tc = new HtmlTableCell();

                    Label lbl = new Label();

                    lbl.Text = dt.Columns[i].ColumnName;

                    lbl.ID = "lbl" + dt.Columns[i].ColumnName;

                    tc.Height = "50px";

                    tc.Width = "150px";

                    tc.Controls.Add(lbl);

                    tr.Controls.Add(tc);

                }

                table.Controls.Add(tr);

               

               //creating textboxes for displaying records information 



                for (int j = 0; j < dt.Rows.Count; j++)

                {

                    tr = new HtmlTableRow();

                    for (int k = 0; k < dt.Columns.Count; k++)

                    {

                        tc = new HtmlTableCell();

                        TextBox txt = new TextBox();

                        txt.ID = "txt" + j + k;

                        txt.Text = dt.Rows[j][dt.Columns[k].ToString()].ToString();

                        tc.Controls.Add(txt);

                        tr.Controls.Add(tc);

                    }

                    table.Controls.Add(tr);

                }

                form1.Controls.Add(table);

            }

        }

        catch (Exception ex)

        {

            Response.Write("Please enter a valid table");

        }

    }

No comments:

Post a Comment