Asp.net button click event not working - asp.net

I have a table which is populated programatically. Buttons are also created within the table as it's built. But i can't seem to find a way to get my button click event to work. It just doesn't seem to fire the event.
Any ideas please? I'm new to asp.net.
Here is the code:
using Parse;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace FrogPointCMS
{
public partial class Beacons : System.Web.UI.Page
{
string merchantName;
string myMerchantID;
ParseObject merchantObject;
protected void Page_Load(object sender, EventArgs e)
{
merchantName = Request.QueryString["user"];
myMerchantID = Request.QueryString["merchantID"];
// merchantObject = (ParseObject)Session["Merchant"]; // this works to retrieve objects from another screen
merchantObject = Global.merchantObjectStatic;
if (merchantObject != null)
{
getBeacons();
}
}
public async void getBeacons()
{
MyParseQueries myQuery = new MyParseQueries();
var myBeacons = await myQuery.getMyBeacons(); // get all the beacons
foreach (ParseObject beacon in myBeacons)
{
string aliasName = "";
string offerType = "N/A";
string offerTitle = "";
string offerDescription = "";
var merchantOb = beacon.Get<ParseObject>("merchantObjectId");
var merchantID = merchantOb.ObjectId;
if (merchantID == myMerchantID)
{
if (beacon.ContainsKey("contentObjectID"))
{
ParseObject content = beacon.Get<ParseObject>("contentObjectID"); // get the content object from parse.
offerType = content.Get<string>("offerType");
offerTitle = content.Get<string>("offerTitle");
offerDescription = content.Get<string>("offerDescription");
}
aliasName = beacon.Get<string>("aliasName");
//HERE IS THE PROBLEM AREA WITH THE BUTTON CREATION AND CLICK EVENT
Button assignNameBtn = new Button();
assignNameBtn = new Button();
assignNameBtn.ID = "assignName";
assignNameBtn.Text = "Assign Name";
assignNameBtn.Click += new System.EventHandler(this.assignNameBtn_Click);
// assignNameBtn.OnClientClick = "buttonClickTest2()"; //this works to trigger the java in the html page
// assignNameBtn.OnClientClick = "assignNameBtn_Click()";
Button assignActionBtn = new Button();
assignActionBtn.ID = "assignAction";
assignActionBtn.Text = "Assign Action";
var tr = new HtmlTableRow();
var checkBox = new HtmlTableCell();
var tableCellName = new HtmlTableCell();
var tableCellButton1 = new HtmlTableCell();
var tableCellButton2 = new HtmlTableCell();
var tableCellAction = new HtmlTableCell();
checkBox.InnerHtml = "<input type=\"checkbox\"/>";
tableCellName.InnerText = aliasName;
tableCellButton1.Controls.Add(assignNameBtn);
tableCellButton2.Controls.Add(assignActionBtn);
tableCellAction.InnerText = offerType + " - " + offerTitle + " - " + offerDescription;
tr.Cells.Add(checkBox);
tr.Cells.Add(tableCellName);
tr.Cells.Add(tableCellButton1);
tr.Cells.Add(tableCellAction);
tr.Cells.Add(tableCellButton2);
beaconTable.Rows.Add(tr);
}
}
}
void assignNameBtn_Click(object sender, EventArgs e)
{
var btn = (Button)sender; // testing
HtmlTableRow row = (HtmlTableRow)btn.NamingContainer; //testing
// System.Diagnostics.Debug.WriteLine("Clicked");
// assignNameBtn.OnClientClick = "buttonClickTest2()";
Response.Write("It worked");
}
}
}
The table in question startes like this in the .aspx file
<form id="mainform" runat="server">
<table border="0" cellpadding="0" cellspacing="0" id="beaconTable" runat="server" >
<tr>
<th class="table-header-check"><a id="toggle-all" ></a> </th>
<th class="table-header-repeat line-left minwidth-1">Beacon Name </th>
<th class="table-header-repeat line-left minwidth-1" style="width: 113px"></a></th>
<th class="table-header-repeat line-left">Assigned Action</th>
<th class="table-header-repeat line-left"></a></th>
</tr>

You should use without parentheses
assignNameBtn.Click += assignNameBtn_Click;

Related

How to categorize product by it's types in Asp.net using Webforms

I want to sort the products by their type, using dropdownlist.
products by types isn't working when i select it in dropdown list.
stored procedure of ProductByType:
Public List<Product> GetProductsByType(int typeId)
{
try
{
using (GarageDBEntities db = new GarageDBEntities())
{
//select * from table where condition is required type
List<Product> products = (from x in db.Products
where x.TypeId == typeId
select x).ToList();
return products;
}
}
catch (Exception)
{
return null;
}
}
Index page code to display products:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
}
private void FillPage()
{
//Get a lsit of all products in DB
ProductModel productModel = new ProductModel();
List<Product> products = productModel.GetAllProducts();
//Make sure products exists in the database
if (products != null)
{
//Create a new Panel with an ImageButton and 2 labels for each Product
foreach (Product product in products)
{
Panel productPanel = new Panel();
ImageButton imageButton = new ImageButton();
Label lblName = new Label();
Label lblPrice = new Label();
//Set childControls properties
imageButton.ImageUrl = "~/Images/Products/" + product.Image;
imageButton.CssClass = "productImage";
imageButton.PostBackUrl = "~/Pages/Product.aspx?id=" + product.Id;
lblName.Text = product.Name;
lblName.CssClass = "productName";
lblPrice.Text = "₹" + product.Price;
lblPrice.CssClass = "productPrice";
//Add child controls to Panel
productPanel.Controls.Add(imageButton);
productPanel.Controls.Add(new Literal { Text = "<br />" });
productPanel.Controls.Add(lblName);
productPanel.Controls.Add(new Literal { Text = "<br />" });
productPanel.Controls.Add(lblPrice);
//Add dynamic Panels to static Parent panel
pnlProducts.Controls.Add(productPanel);
}
}
else
{
//No products found
pnlProducts.Controls.Add(new Literal { Text = "No Products Found!" });
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ProductModel productModel = new ProductModel();
List<Product> products = productModel.GetProductsByType(Convert.ToInt32(DropDownList1.SelectedItem.Value));
foreach (Product product in products)
{
Panel productPanel = new Panel();
ImageButton imageButton = new ImageButton();
Label lblName = new Label();
Label lblPrice = new Label();
//Set childControls properties
imageButton.ImageUrl = "~/Images/Products/" + product.Image;
imageButton.CssClass = "productImage";
imageButton.PostBackUrl = "~/Pages/Product.aspx?id=" + product.Id;
lblName.Text = product.Name;
lblName.CssClass = "productName";
lblPrice.Text = "₹" + product.Price;
lblPrice.CssClass = "productPrice";
//Add child controls to Panel
productPanel.Controls.Add(imageButton);
productPanel.Controls.Add(new Literal { Text = "<br />" });
productPanel.Controls.Add(lblName);
productPanel.Controls.Add(new Literal { Text = "<br />" });
productPanel.Controls.Add(lblPrice);
//Add dynamic Panels to static Parent panel
pnlProducts.Controls.Add(productPanel);
}
}
}
It always showing all the products even tho when I select product type.
As shown in image, I selected "Engine Oil" but it showing all the products.
I want it to show particular products only of the selected product type chosen in dropdownlist.
Try add the PostBack validation in your Page_Load event:
C# Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillPage();
}
}
Most likely, when selecting an item in the dropdownlist, a postback is generated which will call PageLoad and reload all the products, to avoid this the PostBack validation is usually set
Make sure to use the AutoPostBack="True" flag in the <asp:DropDownList /> control

How to get HTML for ASP.NET webrequest

I want to get the source code of this page.
string adres = "https://betorder.com/Sports.html";
WebRequest gelenIstek = HttpWebRequest.Create(adres);
WebResponse gelenCevap;
using (gelenCevap = gelenIstek.GetResponse())
{
using (StreamReader donenDeger = new StreamReader(gelenCevap.GetResponseStream()))
{
string gelenBilgi = donenDeger.ReadToEnd();
string gonder = gelenBilgi;
div.InnerHtml = gonder;
}
}
Use http schema to make a request and add the html to some div, like below:
ASPX page
<form id="form1" runat="server">
<asp:Panel runat="server" ID="pnlHtml"></asp:Panel>
</form>
Your code-behind:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
var adres = "http://betorder.com/Sports.html";
var gelenIstek = HttpWebRequest.Create(adres);
WebResponse gelenCevap;
using (gelenCevap = gelenIstek.GetResponse())
{
using (var donenDeger = new StreamReader(gelenCevap.GetResponseStream()))
{
var response = donenDeger.ReadToEnd();
var divcontrol = new HtmlGenericControl
{
TagName = "div",
InnerHtml = response
};
pnlHtml.Controls.Add(divcontrol);
}
}
}

asp.net button causes posts back but doesn't fire event

I have an ASP button on my page that is supposed to trigger an event on post back. This used to work but has stopped working on every single page that the search form is on. This particular code has not been updated since I got it all set up and working. The button code looks like:
<asp:Button id="search_button" class="search_button" runat="server" OnClick="search_button_click" />
And the post back event code looks like:
protected void search_button_click(Object sender, EventArgs e)
{
SessionHandler.sqlSearchTerm = searchBox.Text;
if (Int32.Parse(searchCatDdl.SelectedValue.ToString()) > 0)
{
SessionHandler.search_mcat_id = searchCatDdl.SelectedValue.ToString();
}
else
{
SessionHandler.search_mcat_id = "0";
}
Response.Redirect("/search.aspx");
Response.End();
}
I tried replacing the code inside of the event with just Response.Write("Hit");, but it never triggered at all. The page does post back though. There are no extra </form> tags on the page (or any page), leaving just one open form tag and one closing form tag. And like I said, this used to work but now is not.
The only code in the Page_Load method is code that creates drop down options for the search form (which has always worked and still does). There's nothing that would end the output or functionality. I'm trying to get debugging ideas as to how to figure out why this would stop working. I've tried to get the ID of the object used to cause post back but it's coming up blank. Then again, maybe I'm doing it wrong. In the Page_Load method, I did something along the lines of `Request["__(something)"];'. I don't remember exactly what it was, but it was setting that to a string variable which was supposed to have the object ID in it. Anyway, any help would be greatly appreciated.
EDIT
I also want to point out that if I change the OnClick attribute of my button to something that does not exist, it does err out. So it seems as if things are set correctly as I have them (to me, anyway). Also, every other control on the site still works and fires it's post back event.
Here is the panel my control is in:
<asp:Panel cssClass="search_items" id="pnlSearchButton" runat="server" DefaultButton="search_button">
<div class="search_bar">
<table>
<tr>
<td width="200"><h3 class="title">auction items</h3></td>
<td width="230"><asp:TextBox ID="searchBox" runat="server" placeholder="Search" name="search" /></td>
<td width="220">
<div class="select_cont option-set" id="filters">
<asp:DropDownList runat="server" ID="searchCatDdl" cssClass="option-set clearfix" data-filter-group="selectset">
</asp:DropDownList>
</div>
</td>
<td width="70"><asp:Button id="search_button" cssClass="search_button" runat="server" OnClick="search_button_click" /></td>
<td>
<a class="search_icon icon_collapse" id="toggle4"></a>
<div class="search_icon divider"></div>
<div class="search_icon divider"></div>
</td>
</tr>
</table>
</div>
</asp:Panel>
At the top of my page:
<%# Master Language="C#" MasterPageFile="~/master-pages/Site.Master" AutoEventWireup="true" CodeFile="HeaderFooter.master.cs" Inherits="master_pages.HeaderFooter" %>
The entire code behind for this particular page:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CowansRedesign.master_pages
{
public partial class HeaderFooter : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!String.IsNullOrEmpty(Request.QueryString["logout"]))
{
SessionHandler.mailId = "";
SessionHandler.mailName = "";
SessionHandler.mailFirstName = "";
}
if (!String.IsNullOrEmpty(SessionHandler.mailId) && !String.IsNullOrEmpty(SessionHandler.mailFirstName) && Request.ServerVariables["SCRIPT_NAME"].ToString() != "/default.aspx")
{
if (hiName != null) {
hiName.Text = "Hi " + SessionHandler.mailFirstName;
}
}
}
if (!IsPostBack && searchCatDdl != null)
{
Dictionary<string, string> mainCatList = new Dictionary<string, string>();
mainCatList.Add("0", "All Categories");
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["wesdb1SQL"].ToString()))
using (SqlCommand strSQL = conn.CreateCommand())
{
strSQL.CommandText = "Select mcat_id, mcat_name " +
"From tblMcat " +
"ORDER BY mcat_name ASC";
try
{
conn.Open();
using (SqlDataReader itemReader = strSQL.ExecuteReader())
{
while (itemReader.Read())
{
mainCatList.Add(itemReader["mcat_id"].ToString(), itemReader["mcat_name"].ToString());
}
itemReader.Close();
}
}
catch (Exception e1)
{
Console.WriteLine(e1.ToString());
//Response.Write(e.ToString());
}
finally
{
conn.Close();
}
}
searchCatDdl.DataSource = mainCatList;
searchCatDdl.DataTextField = "Value";
searchCatDdl.DataValueField = "Key";
searchCatDdl.DataBind();
}
}
protected void overlay_itemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
bool isSaleOnline = Public.isSaleOnline(DataBinder.Eval(e.Item.DataItem, "EventSaleId").ToString());
bool isSaleLotted = Public.isSaleLotted(DataBinder.Eval(e.Item.DataItem, "EventSaleId").ToString());
Image overlayImage = (Image)e.Item.FindControl("overlayImage");
HyperLink auctionLink = (HyperLink)e.Item.FindControl("viewAuction");
HyperLink regLink = (HyperLink)e.Item.FindControl("viewReg");
HyperLink catalogLink = (HyperLink)e.Item.FindControl("viewCatalog");
Label slide_date = (Label)e.Item.FindControl("slide_date");
Label EventName = (Label)e.Item.FindControl("EventName");
EventName.Text = DataBinder.Eval(e.Item.DataItem, "EventName").ToString();
overlayImage.ImageUrl = "http://cowansauctions.com/webimages/events/" + DataBinder.Eval(e.Item.DataItem, "EventMain");
string[] formats = { "MM/dd/yyyy", "MM-dd-yyyy", "yyyy-MM-dd HH:mm:ss", "yyyyMMdd HH:mm:ss" };
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime formattedDate;
//Response.Write(DataBinder.Eval(e.Item.DataItem, "homeDate").ToString());
//Response.End();
DateTime.TryParseExact(DataBinder.Eval(e.Item.DataItem, "homeDate").ToString(), formats, culture, DateTimeStyles.None, out formattedDate);
slide_date.Text = String.Format("{0:MM.dd.yy}", formattedDate);
if (DataBinder.Eval(e.Item.DataItem, "EventSaleId").ToString().Length >= 1)
{
auctionLink.Text = "More about the auction >";
auctionLink.NavigateUrl = "/auctions/details.aspx?id=" + DataBinder.Eval(e.Item.DataItem, "EventId");
if (isSaleOnline)
{
catalogLink.Text = "View Catalog >";
catalogLink.NavigateUrl = "/auctions/catalog.aspx?id=" + DataBinder.Eval(e.Item.DataItem, "EventSaleId") + "" + (!String.IsNullOrEmpty(DataBinder.Eval(e.Item.DataItem, "EventStartPage").ToString()) ? "&page=" + DataBinder.Eval(e.Item.DataItem, "EventStartPage") : "");
regLink.Text = "Register to bid online >";
regLink.NavigateUrl = "/auctions/live-bid.aspx";
}
else
{
if (Convert.ToBoolean(DataBinder.Eval(e.Item.DataItem, "EventRegister")))
{
regLink.Text = "Register to bid online >";
regLink.NavigateUrl = "/auctions/live-bid.aspx";
}
if (isSaleLotted)
{
catalogLink.Text = "View Catalog >";
catalogLink.NavigateUrl = "/auctions/catalog.aspx?id=" + DataBinder.Eval(e.Item.DataItem, "EventSaleId") + "" + (!String.IsNullOrEmpty(DataBinder.Eval(e.Item.DataItem, "EventStartPage").ToString()) ? "&page=" + DataBinder.Eval(e.Item.DataItem, "EventStartPage") : "");
}
}
}
else
{
catalogLink.Text = "View Event Details >";
catalogLink.NavigateUrl = "/event.aspx?id=" + DataBinder.Eval(e.Item.DataItem, "EventId");
auctionLink.Visible = false;
regLink.Visible = false;
}
}
}
protected void search_button_click(Object sender, EventArgs e)
{
SessionHandler.sqlSearchTerm = searchBox.Text;
if (Int32.Parse(searchCatDdl.SelectedValue.ToString()) > 0)
{
SessionHandler.search_mcat_id = searchCatDdl.SelectedValue.ToString();
}
else
{
SessionHandler.search_mcat_id = "0";
}
Response.Redirect("/search.aspx");
Response.End();
}
public static string StripHTML(string htmlString)
{
string pattern = #"<(.|\n)*?>";
return Regex.Replace(htmlString, pattern, string.Empty);
}
}
}
Well, I finally found the issue. I was thinking back and realized the very last change I made was adding Google's Tag Manager code to the website for some SEO tracking. That code turned out to be what was causing this one thing to stop working. I have no clue why. I removed it and everything is working.
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-5XQX2B"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-fdsafdsa');</script>
<!-- End Google Tag Manager -->

Viewstate and Tab container

I have the following code for a tab container and i am able to create a tab dynamically but as soon as i try to click to add another tab the previous tab disappears, i can't figure out how to keep viewstate, can someone please help me with this.
test5.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test5.aspx.cs" Inherits="test5" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<cc1:tabcontainer id="TabContainer1" visible="true" runat="server" Height="150px">
<cc1:TabPanel ID="Tab0" runat="server" HeaderText="Step 1">
<ContentTemplate>
Test
<asp:Button ID="add" Text="Add" OnClick="add_Click" runat="server" />
</ContentTemplate>
</cc1:TabPanel>
</cc1:tabcontainer>
</div>
</form>
</body>
</html>
test5.aspx.cs
using AjaxControlToolkit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class test5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void add_Click(object sender, EventArgs e)
{
int currentTab = TabContainer1.ActiveTabIndex;
int nextTab = currentTab + 1;
Button btn = new Button();
btn.ID = "Add" + nextTab.ToString();
btn.Text = "Add";
btn.Click += new EventHandler(add_Click);
TabPanel t = new TabPanel();
t.ID = "Tab" + nextTab;
t.HeaderText = "Tab:" + nextTab;
t.Controls.Add(btn);
TabContainer1.Tabs.Add(t);
}
}
Here's what I'd do:
Wrap the following code:
Button btn = new Button();
btn.ID = "Add" + nextTab.ToString();
btn.Text = "Add";
btn.Click += new EventHandler(add_Click);
TabPanel t = new TabPanel();
t.ID = "Tab" + nextTab;
t.HeaderText = "Tab:" + nextTab;
t.Controls.Add(btn);
TabContainer1.Tabs.Add(t);
Into its own method called RenderDynamicTabs(int nextTab)
At the end of add_Click, add this code:
if(null == ViewState["NumDynamicControls"])
{
ViewState["NumDynamicControls"] = 0;
}
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"]);
dynamicControlCount++;
In Page_Load, add the following:
if(null != ViewState["NumDynamicControls"])
{
// There are controls that need to be re-generated
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"]);
for(int i = 1; i <= dynamicControlCount; i++)
{
RenderDynamicTabs(i);
}
}
That should both store and re-render your controls after each PostBack.
Finally, to avoid duplication of code, in add_Click, replace the code you copy-pasted into RenderDynamicTabs with just a call to RenderDynamicTabs(nextTab);.
i removed the additions i added before, but here is what i got so far
using AjaxControlToolkit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class test5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (null != ViewState["NumDynamicControls"])
{
// There are controls that need to be re-generated
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"].ToString());
for (int i = 1; i <= dynamicControlCount; i++)
{
RenderDynamicTabs(i);
}
}
}
public void RenderDynamicTabs(int nextTab)
{
Button btn = new Button();
btn.ID = "Add" + nextTab.ToString();
btn.Text = "Add";
btn.Click += new EventHandler(add_Click);
TabPanel t = new TabPanel();
t.ID = "Tab" + nextTab;
t.HeaderText = "Tab:" + nextTab;
t.Controls.Add(btn);
TabContainer1.Tabs.Add(t);
}
protected void add_Click(object sender, EventArgs e)
{
int currentTab = TabContainer1.ActiveTabIndex;
int nextTab = currentTab + 1;
RenderDynamicTabs(nextTab);
if (null == ViewState["NumDynamicControls"])
{
ViewState["NumDynamicControls"] = 0;
}
var dynamicControlCount = int.Parse(ViewState["NumDynamicControls"].ToString());
dynamicControlCount = dynamicControlCount + 1;
}
}

How to use Using the HtmlAgilityPack to get table value

http://www.dsebd.org/latest_PE_all2_08.php
i work on asp.net C# web.Above url contain some information ,i need to save them in my database and also need to save then in specified location as xml format.This url contain a table.I want to get this table value but how to retrieve value from this html table.
HtmlWeb htmlWeb = new HtmlWeb();
// Creates an HtmlDocument object from an URL
HtmlAgilityPack.HtmlDocument document = htmlWeb.Load("http://www.dsebd.org/latest_PE_all2_08.php");
I need help to get table information from this document .How to save this table value.Show me some syntax
public partial class WebForm3 : System.Web.UI.Page
{
private byte[] aRequestHTML;
private string myString = null;
protected System.Web.UI.WebControls.Label Label1;
private ArrayList a = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
WebClient objWebClient = new WebClient();
aRequestHTML = objWebClient.DownloadData("http://www.dsebd.org/latest_PE_all2_08.php");
// creates UTf8 encoding object
UTF8Encoding utf8 = new UTF8Encoding();
// gets the UTF8 encoding of all the html we got in aRequestHTML
myString = utf8.GetString(aRequestHTML);
string html = #"
<html><head></head>
<body><div>
<table border=1>
<tr><td>sno</td><td>sname</td></tr>
<tr><td>111</td><td>abcde</td></tr>
<tr><td>213</td><td>ejkll</td></tr>
</table>
<table border=1>
<tr><td>adress</td><td>phoneno</td><td>note</td></tr>
<tr><td>asdlkj</td><td>121510</td><td>none</td></tr>
<tr><td>asdlkj</td><td>214545</td><td>none</td></tr>
</table>
</div></body>
</html>";
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(myString);
DataTable addressAndPhones;
foreach (var table in ParseAllTables(htmlDoc))
{
if (table.Columns.Contains("Trading Code") && table.Columns.Contains("Close Price"))
{
// You found the address and phone number table
addressAndPhones = table;
}
}
}
private static DataTable[] ParseAllTables(HtmlDocument doc)
{
var result = new List<DataTable>();
foreach (var table in doc.DocumentNode.Descendants("table"))
{
result.Add(ParseTable(table));
}
return result.ToArray();
}
private static DataTable ParseTable(HtmlNode table)
{
var result = new DataTable();
var rows = table.Descendants("tr");
var header = rows.Take(1).First();
foreach (var column in header.Descendants("td"))
{
result.Columns.Add(new DataColumn(column.InnerText, typeof(string)));
}
foreach (var row in rows.Skip(1))
{
var data = new List<string>();
foreach (var column in row.Descendants("td"))
{
data.Add(column.InnerText);
}
result.Rows.Add(data.ToArray());
}
return result;
}
}
In this way u can easily create a DataTable and then can save is DataBase.

Resources