Displaying a table information dynamically ,without using any controls

venkyshwe8-8686
Posted by venkyshwe8-8686 under ASP.NET category on | Points: 40 | Views : 2038
I want to show ,how to display the table information which is in the database,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");
}
}

i think this article may helps the developers

Comments or Responses

Posted by: T.saravanan on: 2/10/2011 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi,

Nice Try...
Just change the integer variable in your code for (int x= 0; x< dt.Columns.Count; x++) because in our website 'i' is declared as italic format.

One doubt from your question...
Displaying a table information dynamically ,without using any controls then why are you using TextBox Control in your code. :)

Cheers :)





Login to post response