I have a json that I want to convert to a HTML grid view on the server side and return the HTML as a string
StringBuilder sb = new StringBuilder();
var serializer = new JavaScriptSerializer();
string g = serializer.Serialize(ox)
//here convert g to html table
sb.Append(g);
return sb.ToString();
private String Serialize2HTMLTable(List<conversion> ox)
{
var serializer = new JavaScriptSerializer();
DataTable dt = (DataTable)JsonConvert.DeserializeObject(serializer.Serialize(ox), (typeof(DataTable)));
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
//Create a table
Table tbl = new Table();
tbl.BorderStyle = BorderStyle.Solid;
tbl.BorderWidth = 1;
//Create column header row
TableHeaderRow thr = new TableHeaderRow();
foreach (DataColumn col in dt.Columns)
{
TableHeaderCell th = new TableHeaderCell();
th.Text = col.Caption;
thr.Controls.Add(th);
}
tbl.Controls.Add(thr);
//Create table rows
foreach (DataRow row in dt.Rows)
{
TableRow tr = new TableRow();
foreach (var value in row.ItemArray)
{
TableCell td = new TableCell();
td.BorderStyle = BorderStyle.Solid;
td.BorderWidth = 1;
td.Text = value.ToString();
tr.Controls.Add(td);
}
tbl.Controls.Add(tr);
}
tbl.RenderControl(w);
return sw.ToString();
}
Related
I have an export function in my asp.net application. I want to remove all the white spaces/nulls in the list. Any way to trim it?
This is how my code looks like:
My GetData methode from the Database:
public void GetData()
{
try
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["GS1connectionString"].ConnectionString);
connection.Open();
using (SqlCommand sqlCmd = new SqlCommand("DAtabase.dbo.SP_EXPORT", connection)) //Extract data: no cons first and cons after
{
sqlCmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["TaskTable"] = dt;
}
}
}
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('No data found, try again');", true);
}
}
Clean dataTable methode:
public DataTable removeEmptyColumns(DataTable table)
{
int k = 0, l = 0;
DataTable dtResult = table.Clone();
DataRow row = dtResult.NewRow();
row = dtResult.NewRow();
for (k = 0; k < table.Rows.Count; k++)
{
for (l = 0; l < table.Rows.Count; l++)
{
if (k == l)
row[k] = table.Rows[k][l];
}
}
dtResult.Rows.Add(row);
dtResult.AcceptChanges();
return dtResult;
}
The Export to excel button:
protected void Button_Export_DS_Click(object sender, EventArgs e)
{
GetData();
DataTable dat = new DataTable();
DataTable dtNew = new DataTable();
dat = (DataTable)Session["TaskTable"];
dtNew = removeEmptyColumns(dat);
//Export to excel from datatable stored in a session
if (dtNew.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet" + i++);
worksheet.Cells["A1"].LoadFromDataTable(dtNew, true);
worksheet.Cells.AutoFitColumns();
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename=DS_Export.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}
}
I have an export function in my asp.net application. I want to remove all the white spaces/nulls in the list. Any way to trim it?
You copy and paste this function:
public DataTable removeEmptyColumns(DataTable table)
{
int k = 0, l = 0;
DataTable dtResult = table.Clone();
DataRow row = dtResult.NewRow();
row = dtResult.NewRow();
for (k = 0; k < table.Rows.Count ; k++)
{
for (l = 0; l < table.Rows.Count; l++)
{
if (k == l)
row[k] = table.Rows[k][l];
}
}
dtResult.Rows.Add(row);
dtResult.AcceptChanges();
return dtResult;
}
And then use the function like this:
DataTable dt = new DataTable();
DataTable dtNew = new DataTable();
dt = (DataTable)Session["TaskTable"];
dtNew = removeEmptyColumns(dt);
After that, use this dtNew in this:
if (dtNew.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet" + i++);
worksheet.Cells["A1"].LoadFromDataTable(dtNew, true);
worksheet.Cells.AutoFitColumns();
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename=Export.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}
I have a bound drop down list that I would like to place into a Table Cell. I am used to Labels and Text Boxes but I cannot seem to get the syntax working on this one. This code is inside of a Webmethod and my output has to be just the html. Thank you.
[System.Web.Services.WebMethod]
public static string gatherSurchargeData(string PriceListItemID, string ProdID, string ColorCode)
{
DataTable GetProductSizes = new DataTable();
GetProductSizes = DataLayer.PricingToolDL.getProductSizes(ProdID, ColorCode);
DataTable dt = new DataTable();
dt = DataLayer.PricingToolDL.getScharge(PriceListItemID);
Table tblScharges = new Table();
tblScharges.ID = "tblScharges";
TableHeaderRow th = new TableHeaderRow();
TableHeaderCell thSizeScharge = new TableHeaderCell();
thSizeScharge.Text = "Size";
th.Cells.Add(thSizeScharge);
tblScharges.Rows.Add(th);
int i = 0;
while (i <= dt.Rows.Count - 1)
{
TableRow tr = new TableRow();
tr.ID = "tableTr" + i;
TableCell tcSizeScharge = new TableCell();
DropDownList ddl = new DropDownList();
ddl.DataSource = GetProductSizes;
ddl.DataTextField = "FitSize";
ddl.DataValueField = "FitSize";
ddl.DataBind();
//string dtMovexSKU = dt.Rows[i]["MovexSKU"].ToString();
//DataRow[] GetProductSizesMovexSKU = GetProductSizes.Select("MovexSKU Like'" + dtMovexSKU + "'");
//tcSizeScharge.ID = "tcSizeScharge" + i;
//tcSizeScharge.Text = GetProductSizesMovexSKU[0][1].ToString();
tr.Cells.Add(tcSizeScharge);
tblScharges.Rows.Add(tr);
i++;
}
string html = "";
using (StringWriter sw = new StringWriter())
{
tblScharges.RenderControl(new HtmlTextWriter(sw));
html = sw.ToString();
}
return html;
}
The commented lines would be the code I would use if I were only wanting text to appear if that helps.
You need to add control in tablecell like this
tcSizeScharge.Controls.Add(ddl);
I have an aspx page that contains a grid-view. The data-source for the gird-view is a datatable.
I want the last column in the grid view to contain a list of hyperlinks. I cannot figure out how to store or display this data
private void retrieveGroups()
{
// UserTab is a DataTable
// UserGrid is a GridView
UserTab.Columns.Add("LoginName", typeof(string));
UserTab.Columns.Add("DisplayName", typeof(string));
UserTab.Columns.Add("Kind", typeof(string));
UserTab.Columns.Add("Count", typeof(string));
UserTab.Columns.Add("Managers", typeof(string));
UserGrid.DataSource = UserTab;
SqlCommand cmd = FmaDb.makeCmd(FmaDb.SubDB.FMA_CUSTOMER, "fetchGroupIds", CommandType.StoredProcedure,
delegate(SqlCommand inCmd) { inCmd.Parameters.Add("#siteid", SqlDbType.Int); });
List<int> groupIds = new List<int>();
FmaDb.runReadCmd(cmd, delegate(SqlCommand inCmd) { inCmd.Parameters["#siteid"].Value = int.Parse(LFList.SelectedItem.Value); }, null,
delegate(SqlDataReader qrdr) { groupIds.Add(FmaDb.getDbInt(qrdr, 0)); });
UserGrid.Visible = true;
HyperLinkField hf = new HyperLinkField();
BoundField bf = new BoundField();
hf.HeaderText = "Login";
hf.DataTextField = "LoginName";
hf.DataNavigateUrlFields = new String[1] { "login" };
hf.DataNavigateUrlFormatString = "~/fausage.aspx?cn=login&lg={0}&ad=" + ad + "&as=" + aStatus;
UserGrid.Columns.Add(hf);
bf = new BoundField();
bf.HeaderText = "Name";
bf.DataField = "DisplayName";
UserGrid.Columns.Add(bf);
bf = new BoundField();
bf.HeaderText = "Type";
bf.DataField = "Kind";
UserGrid.Columns.Add(bf);
bf = new BoundField();
bf.HeaderText = "# Members";
bf.DataField = "Count";
UserGrid.Columns.Add(bf);
bf = new BoundField();
bf.HeaderText = "Managers";
bf.DataField = "Managers";
UserGrid.Columns.Add(bf);
foreach (int gId in groupIds)
{
Advisor advGroup = new Advisor(gId);
List<HyperLink> linkList = new List<HyperLink>();
advGroup.fetch();
if ((advGroup.Kind == AdvisorKind.Branch) || (advGroup.Kind == AdvisorKind.Team))
{
List<AdvisorMembership> members = advGroup.MyMembers(null, false);
if (advGroup.Kind == AdvisorKind.Branch)
{
List<AdvisorMembership> mgrs = advGroup.MyMembers(null, true);
HyperLink link;
foreach (AdvisorMembership m in mgrs)
{
if (m.MemberCanLoginAsContainer)
{
link = new HyperLink();
link.Text = m.Member.LoginName;
link.NavigateUrl = "~/fausage.aspx?cn=login&lg=" + m.Member.LoginName + "&ad=" + ad + "&as=" + aStatus;
link.Target = "blank";
linkList.Add(link);
}
}
}
UserTab.Rows.Add(advGroup.LoginName, advGroup.DisplayName, advGroup.Kind.ToString(), members.Count.ToString(), linkList);
}
ViewState["DataTable"] = UserTab;
}
}
}
}
i have a database..i am getting my database values in myarraylist..now i want to add this in my datatable column and finally bind it to gridview and show data in webpage..
mycodebehind page
protected void Page_Load(object sender, EventArgs e)
{
ArrayList myArrayList = ConvertDataSetToArrayList();
// Display each item of ArrayList
DataTable dt = new DataTable();
dt.Columns.Add("User Id", Type.GetType("System.String"));
dt.Columns.Add("Problem Name", Type.GetType("System.String"));
dt.Columns.Add("Status", Type.GetType("System.String"));
for (int i = 0; i < 2; i++)
{
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
public ArrayList ConvertDataSetToArrayList()
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM usertable", objsqlconn);
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in myDataSet.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
objsqlconn.Close();
return myArrayList;
}
i have problem in the for loop ..here how i will add rows and values to the columns from arraylist...
Do you mean something like this?
for (int i = 0; i < myArrayList.Count; i++)
{
var row = dt.NewRow();
row[0] = ((DataRow)myArrayList[i])[0];
row[1] = ((DataRow)myArrayList[i])[1];
row[2] = ((DataRow)myArrayList[i])[2];
dt.Rows.Add(row);
}
where indexes 0,1,2... can be replaced by column names "User Id", "Problem Name" and "Status"
I added text boxes dynamically in ASP.Net from server side. By using one example which is shown in followed link
http://www.dotnettips4u.com/2013/03/dynamically-creating-text-boxes-using-c.html.
But I couldn't find out how to retrieve values from those text boxes..
Please help me to come out from this..
Here I am posting my code also..
Client Side Code:
<asp:TextBox ID="NoOfPsngr" runat="server" />
<asp:Button ID="AddP" runat="server" Text="Add Passengers" OnClick="AddP_Click" />
<asp:Panel runat="server" ID="passengerdet">
</asp:Panel>
Server Side Code:
protected void AddP_Click(object sender, EventArgs e)
{
int rowCount = Convert.ToInt32(NoOfPsngr.Text);
Table table = new Table();
table.ID = "PsngrTbl";
//Create the textboxes and labels each time the button is clicked.
for (int i = 0; i < rowCount; i++)
{
TableRow row = new TableRow();
TableCell namelblCell = new TableCell();
Label namelbl = new Label();
namelbl.Text = "Name";
TableCell nameTxtCell = new TableCell();
TextBox nameTxt = new TextBox();
TableCell typelblCell = new TableCell();
Label typelbl = new Label();
typelbl.Text = "Type";
TableCell typeSelectCell = new TableCell();
DropDownList typeSelect = new DropDownList();
ListItem adultItem = new ListItem();
adultItem.Text = "Adult";
adultItem.Value = "Adult";
typeSelect.Items.Add(adultItem);
ListItem childItem = new ListItem();
childItem.Text = "Child";
childItem.Value = "Child";
typeSelect.Items.Add(childItem);
ListItem infantItem = new ListItem();
infantItem.Text = "Infant";
infantItem.Value = "Infant";
typeSelect.Items.Add(infantItem);
TableCell etktlblCell = new TableCell();
Label etktlbl = new Label();
etktlbl.Text = "Eticket No";
TableCell etktTxtCell = new TableCell();
TextBox etktTxt = new TextBox();
//Adding.....
namelblCell.Controls.Add(namelbl);
typelblCell.Controls.Add(typelbl);
etktlblCell.Controls.Add(etktlbl);
nameTxtCell.Controls.Add(nameTxt);
typeSelectCell.Controls.Add(typeSelect);
etktTxtCell.Controls.Add(etktTxt);
nameTxt.ID = "PName" + i;
typeSelect.ID = "PType" + i;
etktTxt.ID = "ETkt" + i;
row.Controls.Add(namelblCell);
row.Controls.Add(nameTxtCell);
row.Controls.Add(typelblCell);
row.Controls.Add(typeSelectCell);
row.Controls.Add(etktlblCell);
row.Controls.Add(etktTxtCell);
table.Rows.Add(row);
}
passengerdet.Controls.Add(table);
}
use javascript like
$('#PsngrTbl').find('input[type=radio]').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue;
var controlName = $(this).attr('name');
if ($('[name=' + controlName + ']:checked').val() == undefined) {
oValue = "";
}
else {
oValue = $('[name=' + controlName + ']:checked').val();
}
});
$('#PsngrTbl').find('input[type=checkbox]').each(function (index, element) {
var o = $(this);
var value;
if (o.on == true) {
value = 1;
}
else {
value = 0;
}
var oID = o.attr("id");
var oValue = value;
});
$('#PsngrTbl').find('textarea').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue = o.val();
});
$('#PsngrTbl').find('select').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue = o.val();
});
It will return all values of controlls of that table