I am using a hashtable to store key-value pairs and I initialize this hashtable (ddl_ht) in the method CreateDropDownLists(). However, when I check the value of "currentItem" in my SelectedIndexChanged method, this value is null. Even though I checked the value of
(string)ddl_ht[key[1]]
in my Watch window and it shows a value (not null). Do you understand why this currentItem is null?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ADONET_namespace;
namespace AddFileToSQL
{
public partial class DataMatch : _Default
{
protected System.Web.UI.WebControls.PlaceHolder phTextBoxes;
protected System.Web.UI.WebControls.PlaceHolder phDropDownLists;
protected System.Web.UI.WebControls.Button btnAnotherRequest;
protected System.Web.UI.WebControls.Panel pnlCreateData;
protected System.Web.UI.WebControls.Literal lTextData;
protected System.Web.UI.WebControls.Panel pnlDisplayData;
protected static string inputfile2;
static string[] headers = null;
static string[] data = null;
static string[] data2 = null;
static DataTable myInputFile = new DataTable("MyInputFile");
static string[] myUserSelections;
static Hashtable ddl_ht = new Hashtable();
// Page Load
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
this.NumberOfControls = 0;
}
}
// Add DropDownList Control to Placeholder
private void CreateDropDownLists()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
DropDownList ddl = new DropDownList();
SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable);
ddl.ID = "DropDownListID " + (counter + 1).ToString();
ddl.DataTextField = "COLUMN_NAME";
ddl.DataValueField = "COLUMN_NAME";
ddl.DataSource = dr;
ddl.DataBind();
//myUserSelections[counter] = "";
ddl.AutoPostBack = true;
ddl.EnableViewState = true; //Preserves View State info on Postbacks
ddl.Style["position"] = "absolute";
ddl.Style["top"] = 100 * counter + 80 + "px";
ddl.Style["left"] = 250 + "px";
ddl.SelectedIndexChanged += new EventHandler(SelectedIndexChanged);
ddl_ht.Add(counter, ddl.SelectedValue);
pnlDisplayData.Controls.Add(ddl);
pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>"));
pnlDisplayData.Visible = true;
pnlDisplayData.FindControl(ddl.ID);
// pnlDropDownList.FindControl(ddl.ID);
dr.Close();
}
}
protected void SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
string[] value=(ddl.SelectedValue).Split(' ');
string[] key = ddl.ID.Split(' ');
string currentItem=(string)ddl_ht[key[1]];
//if (String.IsNullOrEmpty(currentItem))
//{
// ddl_ht.Add(key[1], value[0]);
//}
if (currentItem != ddl.SelectedValue)
{
ddl_ht.Remove(key[1]);
ddl_ht.Add(key[1], ddl.SelectedValue);
}
}
// Add TextBoxes Control to Placeholder
private void RecreateDropDownLists()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
DropDownList ddl = new DropDownList();
SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable);
ddl.ID = "DropDownListID " + (counter + 1).ToString();
ddl.DataTextField = "COLUMN_NAME";
ddl.DataValueField = "COLUMN_NAME";
ddl.DataSource = dr;
ddl.DataBind();
myUserSelections[counter] = "";
dr.Close();
ddl.AutoPostBack = true;
ddl.EnableViewState = true; //Preserves View State info on Postbacks
ddl.Style["position"] = "absolute";
ddl.Style["top"] = 100 * counter + 80 + "px";
ddl.Style["left"] = 250 + "px";
ddl.SelectedIndexChanged += new EventHandler(SelectedIndexChanged);
pnlDisplayData.Controls.Add(ddl);
pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>"));
}
}
// Create TextBoxes and DropDownList data here on postback.
protected override void CreateChildControls()
{
// create the child controls if the server control does not contains child controls
this.EnsureChildControls();
// Creates a new ControlCollection.
this.CreateControlCollection();
// Here we are recreating controls to persist the ViewState on every post back
if (Page.IsPostBack)
{
RecreateDropDownLists();
RecreateLabels();
}
// Create these conrols when asp.net page is created
else
{
PopulateFileInputTable();
CreateDropDownLists();
CreateLabels();
}
// Prevent child controls from being created again.
this.ChildControlsCreated = true;
}
}
}
You are going to have all kinds of threading problems with this setup. Your hashtable is static, and every hit on your website is going to create a new instance of your class on a new thread that will try to access the same hashtable - and since each new hit to the page will initially call CreateDropDownLists, your hashtable will be reinitialzed for every new user to the page.
You shouldn't store your HashTable as a static field of your page class, since it will be shared between sessions because the life cycle of a static variables in ASP.NET is within the life of the appdomain, consider storing it in the ViewState:
private Hashtable ddl_ht
{
get
{
return ViewState["ddl_ht"] as HashTable;
}
set
{
ViewState["ddl_ht"] = value;
}
}
Related
I'm quite new to ASP.NET and I need your help.
I'm programming on an application which should help to fix frequent issues. Users can click the displayed cases if it describes their problem. The application searches for more cases or displays a possible solution.
Now what I need for this is some code which creates the buttons dynamically. I googled some ideas and created some code, however I was not able to get it to work.
It works to create the first selection of buttons with the Default_Load method. Also the OnClick event (ButtonClick_System) works fine which means I get the next selection.
From here it starts messing around. The dynamic buttons created in ButtonClick_System don't have a working OnClick action.
Instead of proceeding with ButtonClick_Question (because of btn_system.Command += ButtonClick_Question; in ButtonClick_System) it seems like it just loads the homepage (maybe something wrong with Page_Load?).
The application should do ButtonClick_Question until no more datasets available in database.
I got the following code:
using System;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using Oracle.DataAccess.Client;
namespace Application
{
public partial class _default : System.Web.UI.Page
{
// Variables
private string app_name = "Application";
// ----- Page_Load ----- //
protected void Page_Load(object sender, EventArgs e)
{
Default_Load();
Session["Application"] = app_name;
}
// ----- Methods ----- //
// Load homepage
public void Default_Load()
{
pnl_default.Visible = true;
pnl_content.Visible = false;
HtmlGenericControl html_default = new HtmlGenericControl();
html_default.TagName = "div";
string cmdString = "(...)";
DataTable dtSystems = OraQueryData(cmdString);
foreach (DataRow dtRow in dtSystems.Rows)
{
int system_id = Convert.ToInt32(dtRow["SYSTEM_ID"]);
string system_name = Convert.ToString(dtRow["SYSTEM_NAME"]);
var btn_system = new Button
{
ID = "btn_" + system_name,
Text = system_name,
CssClass = "sys_buttons"
};
btn_system.Command += ButtonClick_System;
btn_system.CommandArgument = Convert.ToString(system_id);
html_default.Controls.Add(btn_system);
}
plh_default.Controls.Clear();
plh_default.Controls.Add(html_default);
}
// Button OnClick Events
protected void ButtonClick_System(object sender, CommandEventArgs e)
{
pnl_default.Visible = false;
pnl_content.Visible = true;
HtmlGenericControl html_questions = new HtmlGenericControl();
html_questions.TagName = "div";
int system_id = Convert.ToInt32(e.CommandArgument);
string cmdString = "(...)";
DataTable dtQuestions = OraQueryData(cmdString);
foreach (DataRow dtRow in dtQuestions.Rows)
{
string question_id = Convert.ToString(dtRow["FRAGE_ID"]);
string question_text = Convert.ToString(dtRow["FRAGE_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Question;
btn_system.CommandArgument = Convert.ToString(system_id);
html_questions.Controls.Add(btn_system);
}
plh_content.Controls.Clear();
plh_content.Controls.Add(html_questions);
}
protected void ButtonClick_Question(object sender, CommandEventArgs e)
{
pnl_default.Visible = false;
pnl_content.Visible = true;
HtmlGenericControl html_ChildQuestions = new HtmlGenericControl();
html_ChildQuestions.TagName = "div";
int parent_id = Convert.ToInt32(e.CommandArgument);
string cmdString = "(...)";
DataTable dtChildQuestions = OraQueryData(cmdString);
foreach (DataRow dtRow in dtChildQuestions.Rows)
{
string question_id = Convert.ToString(dtRow["FRAGE_ID"]);
string question_text = Convert.ToString(dtRow["FRAGE_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Question;
btn_system.CommandArgument = question_id;
html_ChildQuestions.Controls.Add(btn_system);
}
plh_content.Controls.Clear();
plh_content.Controls.Add(html_ChildQuestions);
}
// ----- Oracle Data Query Methods ----- //
// Create and execute query on database
public static DataTable OraQueryData(string cmdString)
{
string conString = ConfigurationManager.AppSettings["Connection"];
OracleConnection oraCon = new OracleConnection(conString);
OracleCommand oraCmd = new OracleCommand(cmdString, oraCon);
OracleDataAdapter oraDtAd = new OracleDataAdapter(oraCmd.CommandText, oraCon);
DataTable dt = new DataTable();
oraCon.Open();
oraDtAd.Fill(dt);
oraCon.Close();
return dt;
}
}
}
If I've understood the issue correctly I think you're using the wrong controls for the wrong usages.
What I'd suggest you need to do is bind the collection of FAQ records to a repeater or some other data set display control. You can then have an event on the repeater which can handle which record ID has been clicked, post back with that value and refresh the collection of data from that (maybe in another repeater). Don't dynamically create buttons and bind events to them otherwise you will end up in a mess.
Hope this helps.
I am new to windows application.I have a table in which there are two fields namely,Title and Type.
In Type field i have two values "O" & "T".
Now i have to populate a datagrid with this table Title as first column and in second column depending on the Type field value i have to place a control i.e when Type field will have "O" at that time i have to place a combobox in that column and when it is "T" i have to place a text Box
i have tried a lot and googled a lot but both controls in same column is quite difficult for me as a beginner.
Plz help me with this requirement.
this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ERP_Ship.App_Code.Fleet_Person;
using ERP_Ship.App_Code.Appraisal;
using ERP_Ship.Forms.Master;
using ERP_Ship.App_Code.Common;
using ERP_Ship.App_Code.Vessel_Hardening_Measures;
namespace ERP_Ship.Forms.Reports
{
public partial class Vessel_Hardening_Measures : Form
{
// ? //
private DataSet ds = new DataSet("myDs");
private DataTable dt = new DataTable("Apprdtl");
//Define controls must be add to data grid.
private Label lblControl = new Label();
private TextBox txtControl = new TextBox();
private ComboBox cboControl = new ComboBox();
//Capture the clicked cell
private DataGrid.HitTestInfo hitTestGrid;
//Control definishion to add to DataGrid
DataGridTableStyle dataGridStyle = new DataGridTableStyle();
DataGridTextBoxColumn dataGridLableTitle = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle1 = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle2 = new DataGridTextBoxColumn();
//DataGridTextBoxColumn dataGridLable = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridTextBox = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridComboBox = new DataGridTextBoxColumn();
private System.Windows.Forms.DataGrid gv_Appraisal;
#region Form Level Variables
string _strName;
string _strCDCNo;
//DataTable dt = new DataTable();
// OracleConnection con1 = new OracleConnection(ConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString.ToString());
I_Common objCommon = new I_Common();
DataTable dt1 = new DataTable("dt1");
#endregion
#region Public Properties
public string SearchName
{
set
{
_strName = value;
}
get
{
return _strName;
}
}
public string SearchCDCNo
{
set
{
_strCDCNo = value;
}
get
{
return _strCDCNo;
}
}
#endregion
public Vessel_Hardening_Measures()
{
InitializeComponent();
InitializeControls();
Load_Year();
//for (int index = 0; index <= gv_Appraisal.Columns.Count - 1; index++)
//{
// gv_Appraisal.Columns[index].DataPropertyName = gv_Appraisal.Columns[index].Name;
//}
//gv_Appraisal.AutoGenerateColumns = false;
}
private void InitializeControls()
{
//label property
lblControl.Cursor = Cursors.Hand;
lblControl.ForeColor = Color.Red;
lblControl.Font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic);
//textbox property
txtControl.Cursor = Cursors.Hand;
txtControl.BackColor = Color.WhiteSmoke;
txtControl.ForeColor = Color.DarkSlateBlue;
txtControl.Font = new Font("Arial", 8, FontStyle.Bold);
//textbox events.
txtControl.TextChanged += new EventHandler(txtTextChanged);
string[] dropdownitems = { "Yes", "No", "Not Applicable" };
//Define and add ComboBox rows, will be added to data grid.
for (int i = 0; i < dropdownitems.Count(); i++)
cboControl.Items.Add(dropdownitems[i]);
//combobox property
cboControl.Cursor = Cursors.Hand;
cboControl.DropDownStyle = ComboBoxStyle.DropDownList;
//combobox events.
cboControl.SelectedIndexChanged += new EventHandler(cboSelectedIndexChanged);
}
private void DesignTableStyle()
{
dataGridStyle.PreferredRowHeight = 24;
dataGridStyle.MappingName = "Apprdtl";
gv_Appraisal.TableStyles.Add(dataGridStyle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle1);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle2);
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
//dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridLableTitle.HeaderText = "vhm_id";
dataGridLableTitle.MappingName = "vhm_id";
dataGridLableTitle.Width = 1;
//dataGridLableTitle.Width = 40;
dataGridLableTitle1.HeaderText = "Title";
dataGridLableTitle1.MappingName = "Title";
dataGridLableTitle1.Width = 150;
dataGridLableTitle2.HeaderText = "Type";
dataGridLableTitle2.MappingName = "Type";
dataGridLableTitle2.Width = 1;
//dataGridLableTitle2.Width = 40;
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//dataGridComboBox.HeaderText = "COMBOBOX_COL";
//dataGridComboBox.MappingName = "ComboBox_col";
//dataGridComboBox.Width = 130;
}
private void Load_DNF() // DATA NOT FOUND OF CDC NO
{
try
{
using (BL_Vessel_Hardening_Measures obj_vsl_hardening_measures = new BL_Vessel_Hardening_Measures())
{
DataTable dataTable = new DataTable();
ds = obj_vsl_hardening_measures.Get_Vessel_Hardening_Measures();
dt1 = ds.Tables[0];
DataColumn dc = new DataColumn("vhm_id");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Title");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Type");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
//Create a new column for datatable.
dc = new DataColumn("TextBox_Col", System.Type.GetType("System.String"));
//Add created column to datatable object.
dt.Columns.Add(dc);
DataRow dr;
for (int i = 0; i < dt1.Rows.Count; i++)
{
dr = dt.NewRow();
dr["vhm_id"] = dt1.Rows[i]["vhm_id"];
dr["Title"] = dt1.Rows[i]["Title"];
dr["Type"] = dt1.Rows[i]["Type"];
dr["TextBox_Col"] = "";
//dr["ComboBox_Col"] = "";
dt.Rows.Add(dr);
}
// gv_Appraisal.DataSource = ds.Tables[0];
gv_Appraisal.DataSource = dt;
ds.Tables.Remove("Apprdtl");
ds.Tables.Add(dt);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
cls_Utility.Close_Pending_Form();
Home objHome = new Home();
I_Common.CloseForm(this.MdiParent, this, objHome);
}
private void Reset_Controls()
{
//txt_CDC_NO.Text = "";
//cmb_Name.SelectedIndex = -1;
}
~Vessel_Hardening_Measures()
{
this.Close();
}
private void Vessel_Hardening_Measures_FormClosed(object sender, FormClosedEventArgs e)
{
cls_Utility.Close_Pending_Form();
}
private void Load_Year()
{
try
{
//ddl_Year.DisplayMember = "Year";
//ddl_Year.ValueMember = "Year";
objCommon.Load_Years(ddl_Year, 1);
//string str_year = "";
//str_year = DateTime.Now.AddYears(-1).Year.ToString();
//ddl_Year.Items.Add(str_year);
//str_year = DateTime.Now.Year.ToString();
//ddl_Year.Items.Add(str_year);
// ddl_Year.SelectedIndex = 1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Vessel_Hardening_Measures_Load(object sender, EventArgs e)
{
DesignTableStyle();
Load_DNF();
ERP_Ship.App_Code.Common.I_Common.MdiFormTopPanel("Vessel Hardening Measures", "Vessel Hardening Measures", this.MdiParent, true);
//ERP_Ship.App_Code.Common.I_Common.StatusInfoLabel("Double Click the Search Record to View or Edit", "I", this.MdiParent, true);
}
private void gv_Appraisal_MouseUp(object sender, MouseEventArgs e)
{
hitTestGrid = gv_Appraisal.HitTest(e.X, e.Y);
if (hitTestGrid != null)
{
//Which column of datagrid has been clicked.
//switch (hitTestGrid.Column)
//{
if (hitTestGrid.Column == 3)
{
if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "T")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//Add texbox control to datagrid.
dataGridTextBox.TextBox.Controls.Add(txtControl);
// txtControl.Text = gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString();
txtControl.Focus();
}
else if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "O")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridComboBox.HeaderText = "COMBOBOX_COL";
dataGridComboBox.MappingName = "ComboBox_col";
dataGridComboBox.Width = 130;
//Add combobox control to datagrid.
dataGridComboBox.TextBox.Controls.Add(cboControl);
cboControl.Focus();
//for (int i = 0; i < cboControl.Items.Count; i++)
//{
// if (cboControl.Items[i].ToString() == gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString())
// cboControl.SelectedIndex = i;
//}
}
}
}
}
private void txtTextChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = txtControl.Text;
}
//Combobox selected index changed event.
private void cboSelectedIndexChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = cboControl.Text;
}
}
}
There might be multiple approaches to implement functionality, you are looking for.
I found one sample on this link
Check if approach described there suits to your current requirement needs.
I want to write an windows form application who can do auto data filling in an textbox on the web page and get the corresponding data show on the page one by one. I met a problem that my loop goes too fast and I cannot see the result showing on the page. How can I let the page fully loaded and then go the next loop?
My designer has a textbox which is used to input url, webBrowser to browse the web page, the button is used to lunch the page.
My code are as below. I use "http://finance.yahoo.com/" as testing page. Testing data is in excel format. the data is a row, like " msft, bac, f, aapl".
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string url = textBox1.Text;
var request = (HttpWebRequest)WebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
webBrowser1.DocumentText = content;
}
public void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlElement tbUserid = webBrowser1.Document.GetElementById("mnp-search_box");
//HtmlElement tbPasswd = webBrowser1.Document.GetElementById("pwdInput");
HtmlElement btnSubmit = webBrowser1.Document.GetElementById("yucs-sprop_button");
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
if (tbUserid == null || btnSubmit == null)
{
return;
}
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='d:\\testing file\\list.xls';Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=1\";");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [List$]", con);
DataTable dt = new DataTable();
da.Fill(dt);
/* int i = 0;
do
{
string str = dt.Rows[i][0].ToString();
tbUserid.SetAttribute("value", str);
//System.Threading.Thread.Sleep(10000);
btnSubmit.InvokeMember("click");
evt.WaitOne();
i++;
}
while (i < dt.Rows.Count);
*/
for (int i = 0; i < dt.Rows.Count; i++)
{
string str = dt.Rows[i][0].ToString();
tbUserid.SetAttribute("value", str);
btnSubmit.InvokeMember("click");
Application.DoEvents();
//System.Threading.Thread.Sleep(100);
}
// ((WebBrowser)sender).Dispose();
}
}
}
Ok, so, let's suppose your target page is http://thisis.my/addres.html and when the page has been used to insert a row it redirects to http://thisis.my/secondaddres.html.
First, let's create a List to hold all the data from the table and two strings to hold the concrete addresses:
List<string> rows = new List<string>();
static string fillAddress = "http://thisis.my/addres.html";
static string sentAddress = "http://thisis.my/secondaddres.html";
Second, when the button is pressed load the data in the list and do your first navigation:
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='d:\\testing file\\list.xls';Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=1\";");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [List$]", con);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
string str = dt.Rows[i][0].ToString();
rows.Add(str);
}
webBrowser1.NavigateTo(fillAddress);
}
Ensure that your DocumentCompleted event is hooked thorugh designer or code.
And finally when a document has been fully loaded the do this sequence:
If page == fillAddress
If rows is not empty
Extract row
Fill row
Submit
else
We have finished
else
Navigate to fillAddress
-
public async void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if(e.Url.ToString() == fillAddress)
{
if(rows.Count > 0)
{
HtmlElement tbUserid = webBrowser1.Document.GetElementById("mnp-search_box");
HtmlElement btnSubmit = webBrowser1.Document.GetElementById("yucs-sprop_button");
if (tbUserid == null || btnSubmit == null)
return;
string str = rows[0];
rows.RemoveAt(0);
tbUserid.SetAttribute("value", str);
btnSubmit.InvokeMember("click");
}
else
return;
}
else if(e.Url.ToString() == sentAddress)
webBrowser1.NavigateTo(fillAddress);
}
I have done tons of assumptions but you will get the general idea: get a list of data, navigate, when the page to fill is loaded fill the row and send the data, when the confirmation is done navigate again to the fill form and repeat until no data is left.
I have a simple task. first one Dropdownlist control is there where country name is loaded. After selecting country name, dynamically Dropdownlist will be loaded with corresponding state, after selecting state, dynamically another Dropdownlist will be added with relevant district. the problem is that the dynamically selected-index event is not fired. I searched it so many pages, but not find any suitable answer. can any one answer it for written code.
This code worked fine in static controls. but not dynamic controls.
Can any one correct my code
namespace fireProgram
{
public partial class MindforeSystemTestingProgram : System.Web.UI.Page
{
BALayer objBALayer = new BALayer();
DropDownList ddlState=new DropDownList();
DropDownList ddlDistrict=new DropDownList();
protected void Page_Init(EventArgs e)
{
ddlState.ID = "ddlState";
ddlState.AutoPostBack = true;
ddlState.SelectedIndexChanged += new EventHandler(ddlState_SelectedIndexChanged);
panel1.Controls.AddAt(2, ddlState);
ddlDistrict.ID = "ddlDistrict";
panel1.Controls.AddAt(3, ddlDistrict);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCountry.DataSource = objBALayer.GetCountry();
ddlCountry.DataTextField = "Text";
ddlCountry.DataValueField = "Value";
ddlCountry.DataBind();
}
//else
//{
// ddlState.ID = "ddlState";
// ddlState.AutoPostBack = true;
// ddlState.SelectedIndexChanged += new EventHandler(ddlState_SelectedIndexChanged);
// panel1.Controls.AddAt(2, ddlState);
// //ddlDistrict.ID = "ddlDistrict";
// //panel1.Controls.AddAt(3, ddlDistrict);
//}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
int value = Convert.ToInt32(ddlCountry.SelectedValue);
panel1.Controls.AddAt(2, ddlState);
//DropDownList ddlState = new DropDownList();
//ddlState.AutoPostBack = true;
if (value != 0)
{
ddlState.DataSource = objBALayer.GetState(value);
ddlState.DataTextField = "Text";
ddlState.DataValueField = "Value";
ddlState.DataBind();
}
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
int value = Convert.ToInt32(ddlState.SelectedValue);
//DropDownList ddlDistrict = new DropDownList()
panel1.Controls.AddAt(3, ddlDistrict);
if (value != 0)
{
ddlDistrict.DataSource = objBALayer.GetDistrict(value);
ddlDistrict.DataTextField = "Text";
ddlDistrict.DataValueField = "Value";
ddlDistrict.DataBind();
}
}
}
}
I'm getting the following error after I start debugging my program. Do you know how to fix this?
System.NullReferenceException was unhandled by user code
Message="Object reference not set to an instance of an object."
It is referring to the line:
pnlDropDownList.Controls.Add(ddl);
inside the CreateDropDownLists method. Apparently the ddl must be a null object, even though I initialized ddl just before in this same method. Do you understand why I am receiving this error? See code below...
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ADONET_namespace;
using MatrixApp;
namespace AddFileToSQL
{
public partial class DataMatch : _Default
{
protected System.Web.UI.WebControls.PlaceHolder phTextBoxes;
protected System.Web.UI.WebControls.PlaceHolder phDropDownLists;
protected System.Web.UI.WebControls.Button btnAnotherRequest;
protected System.Web.UI.WebControls.Panel pnlCreateData;
protected System.Web.UI.WebControls.Literal lTextData;
protected System.Web.UI.WebControls.Panel pnlDisplayData;
Panel pnlDropDownList;
protected static string inputfile2;
static string[] headers = null;
static string[] data = null;
static string[] data2 = null;
static DataTable myInputFile = new DataTable("MyInputFile");
static string[] myUserSelections;
// a Property that manages a counter stored in ViewState
protected int NumberOfControls
{
get { return (int)ViewState["NumControls"]; }
set { ViewState["NumControls"] = value; }
}
public void EditRecord(object recordID)
{
SelectedRecordID = recordID;
// Load record from database and show in control
}
protected object SelectedRecordID
{
get
{
return ViewState["SelectedRecordID"];
}
set
{
ViewState["SelectedRecordID"] = value;
}
}
protected void OnPreLoad(object sender, EventArgs e)
{
//Create a Dynamic Panel
pnlDropDownList = new Panel();
pnlDropDownList.ID = "pnlDropDownList";
pnlDropDownList.BorderWidth = 1;
pnlDropDownList.Width = 300;
this.form1.Controls.Add(pnlDropDownList);
}
// Page Load
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
this.NumberOfControls = 0;
}
}
// Add DropDownList Control to Placeholder
private void CreateDropDownLists()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
DropDownList ddl = new DropDownList();
SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable);
ddl.ID = "DropDownListID" + (counter + 1).ToString();
ddl.DataTextField = "COLUMN_NAME";
ddl.DataValueField = "COLUMN_NAME";
ddl.DataSource = dr;
ddl.DataBind();
ddl.AutoPostBack = true;
ddl.EnableViewState = true; //Preserves View State info on Postbacks
ddl.Style["position"] = "absolute";
ddl.Style["top"] = 100 * counter + 80 + "px";
ddl.Style["left"] = 250 + "px";
ddl.SelectedIndexChanged += new EventHandler(this.OnSelectedIndexChanged);
pnlDropDownList.Controls.Add(ddl);
pnlDropDownList.Controls.Add(new LiteralControl("<br><br><br>"));
dr.Close();
}
}
private void CreateLabels()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
Label lbl = new Label();
lbl.ID = "Label" + counter.ToString();
lbl.Text = headers[counter];
lbl.Style["position"] = "absolute";
lbl.Style["top"] = 100 * counter + 50 + "px";
lbl.Style["left"] = 250 + "px";
pnlDropDownList.Controls.Add(lbl);
pnlDropDownList.Controls.Add(new LiteralControl("<br><br><br>"));
}
}
// Add TextBoxes Control to Placeholder
private void RecreateDropDownLists()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
DropDownList ddl = new DropDownList();
SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable);
ddl.ID = "DropDownListID" + (counter + 1).ToString();
ddl.DataTextField = "COLUMN_NAME";
ddl.DataValueField = "COLUMN_NAME";
ddl.DataSource = dr;
ddl.DataBind();
myUserSelections[counter] = "";
dr.Close();
ddl.AutoPostBack = true;
ddl.EnableViewState = false; //Preserves View State info on Postbacks
ddl.Style["position"] = "absolute";
ddl.Style["top"] = 100 * counter + 80 + "px";
ddl.Style["left"] = 250 + "px";
pnlDropDownList.Controls.Add(ddl);
pnlDropDownList.Controls.Add(new LiteralControl("<br><br><br>"));
}
}
// Create TextBoxes and DropDownList data here on postback.
protected override void CreateChildControls()
{
// create the child controls if the server control does not contains child controls
this.EnsureChildControls();
// Creates a new ControlCollection.
this.CreateControlCollection();
// Here we are recreating controls to persist the ViewState on every post back
if (Page.IsPostBack)
{
RecreateDropDownLists();
RecreateLabels();
}
// Create these conrols when asp.net page is created
else
{
PopulateFileInputTable();
CreateDropDownLists();
CreateLabels();
}
// Prevent child controls from being created again.
this.ChildControlsCreated = true;
}
private void AppendRecords()
{
switch (targettable)
{
case "ContactType":
for (int r = 0; r < myInputFile.Rows.Count; r++)
{ ADONET_methods.AppendDataCT(myInputFile.Rows[r]); }
break;
case "Contact":
for (int r = 0; r < myInputFile.Rows.Count; r++)
{ ADONET_methods.AppendDataC(myInputFile.Rows[r]); }
break;
case "AddressType":
for (int r = 0; r < myInputFile.Rows.Count; r++)
{ ADONET_methods.AppendDataAT(myInputFile.Rows[r]); }
break;
default: throw new ArgumentOutOfRangeException("targettable type", targettable);
}
}
// Read all the data from TextBoxes and DropDownLists
protected void btnSubmit_Click(object sender, System.EventArgs e)
{
int cnt = FindOccurence("DropDownListID");
EditRecord("DropDownListID" + Convert.ToString(cnt + 1));
AppendRecords();
pnlDisplayData.Visible = false;
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
(this.btnSubmit_Click);
}
#endregion
}
}
I think it's referring to "pnlDropDownList" being a Null object. That function must be getting called before "pnlDropDownList = new Panel();" in "OnPreLoad". Use breakpoints to step through the source and follow the code-path. I'm sure you'll find this is the case.
You might want to try creating your dynamic controls in PreInit, I have a hunch that the Panel has not yet been initialized and hence the exception
Check out the Page Lifecycle