Reputation: 21
I want to print only the first column, but this code is printing whole table.
What is the correct way of doing so?
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//Populating a DataTable from database.
DataTable dt = this.GetData();
//Building an HTML string.
StringBuilder html = new StringBuilder();
//Table start.
html.Append("<table border = '1'>");
//Building the Header row.
html.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
html.Append("<th>");
html.Append(column.ColumnName);
html.Append("</th>");
}
html.Append("</tr>");
counter = 0;
//Building the Data rows.
foreach (DataRow row in dt.Rows)
{
html.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
html.Append("</td>");
}
Upvotes: 1
Views: 364
Reputation: 171
columnName is the column which you want the results from datatable
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(columnName);
}
Upvotes: 0
Reputation: 7352
The mistake you did is that you are traversing your columns even though you only want to show your first column.
Therefore you need to not traverse the columns - via your foreach loop - but get the first column by using dt.Columns[0]
. Take a look below:
//Get the first column from datatable
var firstColumn = dt.Columns[0];
//Build the Header row.
html.Append("<tr>");
html.Append("<th>");
html.Append(firstColumn.ColumnName);
html.Append("</th>");
html.Append("</tr>");
counter = 0;
//Build the Data rows.
foreach (DataRow row in dt.Rows)
{
html.Append("<tr>");
html.Append("<td>");
html.Append(row[firstColumn.ColumnName]);
html.Append("</td>");
html.Append("</tr>");
}
Upvotes: 1