Event not firing with dynamically placed user control asp.net c# - c#

I’m trying to create a webpage that displays dynamically placed WebUserControls depending on a question type that is returned from and SQL server. When you press a button on the usercontrols it checks the result from the usercontrol using the procedure “CheckResult”. For some reason when you click on the buttons within the usercontrols ("cmdProcess") the Event “CheckResult” does not fire. What am I doing wrong please?
The User control code is: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Testing.Event_Delegate
{
public partial class WebUserControl2 : System.Web.UI.UserControl
{
// Delegate declaration
public delegate void PhotoUploaded(string strFilename, String FailureMessage, string strFabricationNo, string strPartNo, string strBatchNo, string strPartSN, string strSTK_SerialNo, string strSTK_PartNo);
// Event declaration
public event PhotoUploaded Resultresponse;
string questionAsked;
public string QuestionText
{
set { questionAsked = value; }
get { return questionAsked; }
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = QuestionText;
TextBox1.Focus();
}
protected void cmdProcess_Click(object sender, EventArgs e)
{
if (Resultresponse != null)
{
Resultresponse("Passed", "", "", "", "", "", "", "");
}
TextBox1.Text = "";
}
}
}
And the main ASPX page that the usercontrols are placed on is: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Testing.Event_Delegate
{
public partial class WebForm1 : System.Web.UI.Page
{
WebUserControl2 QT2;
WebUserControl3 QT3;
DataTable dtQuestionSet;
protected void Page_Load(object sender, EventArgs e)
{
// all controls need to be rendered every page postback otherwise the rest of the code loses scope.
QT2 = (WebUserControl2)this.LoadControl("WebUserControl2.ascx");
QT3 = (WebUserControl3)this.LoadControl("WebUserControl3.ascx");
if (IsPostBack == false)
{
Session["Counter"] = 0;
Session["QuestionCount"] = 0;
Session["CompletedInsp"] = false;
Session["RunInsp"] = false;
dtQuestionSet = new DataTable();
MakeDataTabledtQuestionSet();
}
else
{
dtQuestionSet = (DataTable)Session["DataTableW"];
//check to see if the inspection process is complete and display pass\fail and log. Else carry on.
if (Convert.ToBoolean(Session["CompletedInsp"]) == true)
{
//Response.Write("Failed");
ModalPopupExtender2.Show();
return;
}
}
Session["DataTableW"] = dtQuestionSet;
}
void CheckResult(string Result, string FailureMessage, string FabricationNo, string PartNo, string BatchNo, string PartSN, string STK_SerialNo, string STK_PartNo)
{
Label1.Text = "You Answered: - " + Result;
if ((Convert.ToInt32(Session["Counter"]))>= Convert.ToInt32(Session["QuestionCount"]))
{
Session["CompletedInsp"] = true;
Session["RunInsp"] = false;
}
else
{
dtQuestionSet = (DataTable)Session["DataTableW"];
}
Session["Counter"] = Convert.ToInt32(Session["Counter"]) + 1;
//If the inspection hasn't been completed carry on and ask next question.
if (Convert.ToBoolean(Session["RunInsp"]) == true)
{
RunInspection();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
protected void cmdStartInspection_Click(object sender, EventArgs e)
{
Session["Counter"] = 0;
GetQuestions();
}
protected void GetQuestions()
{
dtQuestionSet.Clear();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PromptedInspConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("test.GetQuestions", conn);
SqlDataReader dr = null;
cmd.CommandType = CommandType.StoredProcedure;
dr = cmd.ExecuteReader();
while (dr.Read())
{
DataRow drQuestions = dtQuestionSet.NewRow();
drQuestions["QuestionText"] = dr[1].ToString();
drQuestions["ExpectedResponse"] = dr[2].ToString();
drQuestions["QuestionType"] = dr[3].ToString();
dtQuestionSet.Rows.Add(drQuestions);
}
Session["DataTableW"] = dtQuestionSet;
Session["QuestionCount"] = dtQuestionSet.Rows.Count;
conn.Close();
RunInspection();
Session["RunInsp"] = true;
}
protected void RunInspection()
{
//Populate the user controls
switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
{
case "1":
QT2.QuestionText = dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][0].ToString();
QT2.Resultresponse += new WebUserControl2.PhotoUploaded(CheckResult);
break;
case "2":
QT3.QuestionText = dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][0].ToString();
QT3.Resultresponse += new WebUserControl3.PhotoUploaded(CheckResult);
break;
}
//Add the usercontrols to the form
PlaceHolder2.Controls.Add(QT2);
PlaceHolder2.Controls.Add(QT3);
//Need to set the visability of the usercontrol so it only shows the usercontrol that is displaying the question
QT2.Visible = false;
QT3.Visible = false;
switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
{
case "1":
QT2.Visible = true;
break;
case "2":
QT3.Visible = true;
break;
}
}
private void MakeDataTabledtQuestionSet()
{
dtQuestionSet.Columns.Add("QuestionText");
dtQuestionSet.Columns.Add("ExpectedResponse");
dtQuestionSet.Columns.Add("QuestionType");
}
}
}

Try initializing the controls in OnPreInit rather than load. Controls binding is done in OnPreInit.
See the page lifecyle events MSDN Reference

Related

C# DataGridView stuck in button1_Click event?

I am trying to get the cell value in a string from the selected cell in the "Document Number" column in a DataGridView. My code to retrieve data from SharePoint and populate the DataGridView works fine, but I seem to be caught in a loop there? I cannot execute any other methods after populating the DataGridView . I can select a new search term and execute the Button1_Click event again successfully, but I cannot get any other methods to execute?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace BuyersForeverFriend
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string userSearch = textBox1.Text;
button1.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
using (ClientContext ctx = new ClientContext("https://teamsites.nafta.fcagroup.com/sites/PSOAPPS/iws/"))
{
var userInput = textBox1.Text;
Web web = ctx.Web;
List list = web.Lists.GetById(new Guid("61ef6657-eff7-42cb-99e1-8afd590334ec"));
var q = new CamlQuery() { ViewXml = "<View><Query><Where><Contains><FieldRef Name='Item_x0020_Description' /><Value Type='Note'>" + userInput + "</Value></Contains></Where></Query><ViewFields><FieldRef Name='Title' /><FieldRef Name='Topic_x002d_' /><FieldRef Name='Item_x0020_Description' /></ViewFields><QueryOptions /></View>" };
var r = list.GetItems(q);
ctx.Load(r);
ctx.ExecuteQuery();
if (r.Count != 0)
{
var searchResults = new DataTable();
searchResults.Columns.AddRange(new[]
{
new DataColumn("ID"), new DataColumn("Document Number"), new DataColumn("Item Description"), new DataColumn("Topic")});
foreach (var oListItem in r)
{
searchResults.Rows.Add(oListItem["ID"], oListItem["Title"], oListItem["Item_x0020_Description"],
oListItem["Topic_x002d_"]);
}
if (dataGridView1 != null)
{
dataGridView1.DataSource = searchResults;
dataGridView1.Refresh();
dataGridView1.Columns[2].DefaultCellStyle.Format = "dd'/'MM'/'yyyy";
var dataGridViewColumn = dataGridView1.Columns["ID"];
if (dataGridViewColumn != null)
dataGridViewColumn.Visible = false;
}
else
MessageBox.Show("after else statement");
}
}
MessageBox.Show("after sharepoint if statement");
return;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("a cell was clicked");
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
MessageBox.Show("starting routine");
if (dataGridView1.SelectedCells.Count > 0)
{
int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
string a = Convert.ToString(selectedRow.Cells["Document Number"].Value);
MessageBox.Show(a);
textBox2.Text = ("The var =" + a);
}
else MessageBox.Show("if did not end up true");
}
}
}
I failed to initialize these, after adding them to the form method...poof everything works! :
public Form1()
{
InitializeComponent();
dataGridView1.CellClick += dataGridView1_CellClick;
dataGridView1.SelectionChanged += dataGridView1_SelectionChanged;
}

Is there any solution "Gridview shows only one data after update new entry."?

Every time when I click the button only one row will be displayed. But it should show multiple rows. I declare the list after the constructor invoke. I tried with gridview.update() and gridview.refresh() but they didn't work. I could not findout the issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using JournalEntryApp.Model;
namespace JournalEntryApp
{
public partial class NewDocument : Form
{
public NewDocument()
{
InitializeComponent();
}
List<JEFrom> JEFromsList = new List<JEFrom>();
List<JETo> JETosList = new List<JETo>();
JEFrom _jef = null;
private void NewDocument_Load(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
private void addToListButton_Click(object sender, EventArgs e)
{
if (string.Empty== fromAccountTextBox.Text)
{
MessageBox.Show("From Account can not be empty!!!");
}
else if (string.Empty == toAccountTextBox.Text)
{
MessageBox.Show("To Account can not be empty!!!");
}
else
{
_jef = new JEFrom{ FromEntryName= fromAccountTextBox.Text , FromEntryDate= DateTime.Now };
JEFromsList.Add(_jef);
temporaryDataGridView.DataSource = JEFromsList;
fromAccountTextBox.Text = string.Empty;
toAccountTextBox.Text = string.Empty;
}
}
}
}
The temporaryDataGridView cannot detect that you have changed the DataSource. It will only refresh when Datasource has changed.
temporaryDataGridView.DataSource = null;
temporaryDataGridView.DataSource = JEFromsList;
so change the Datasource null first.
Or you can use bindingSource
private void NewDocument_Load(object sender, EventArgs e)
{
this.bindingSource1.DataSource = JEFromsList;
temporaryDataGridView.DataSource = this.bindingSource1;
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
in button_click
JEFromsList.Add(_jef);
bindingSource1.ResetBindings(true);

Update datagrid data in another page's form in Asp.net C#

I am new to asp.net and now I am testing simple methods. I want to edit datagrid in form of another page. Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class mymembertype : System.Web.UI.Page
{
public static int mem_typeid;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["valueid"] != null)
{
mem_typeid = (int)(Session["valueid"]);
string memtype_name = Convert.ToString(Session["valueName"]);
string rate = Convert.ToString(Session["rate"]);
txtmembtype.Text = Convert.ToString(memtype_name);
txtdscrate.Text = rate;
}
}
protected void Insert_membertype_Click(object sender, EventArgs e)
{
funtions fun = new funtions();
if (mem_typeid == null)
{
if (txtmembtype.Text != "")
{
if (txtdscrate.Text != "")
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Insert_membertype(membetype, dscrate);
if (chk)
lblInfo.Text = " saving membertype successful";
else
lblInfo.Text = "Error saving membertype";
}
}
}
else
{
if (txtmembtype.Text != "")
{
if (txtdscrate.Text != "")
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Update_memberType(mem_typeid, membetype, dscrate);
if (chk)
lblInfo.Text = " Updating membertype successful";
else
lblInfo.Text = "Error Updating membertype";
}
}
}
}
here is my update function
public bool Update_memberType(int id, string name, int dsc)
{
string connectionString =
WebConfigurationManager.ConnectionStrings["Spa"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
int memid = id;
string membtype = name;
int dsrate = dsc;
Boolean chk = false;
try
{
myConnection.Open();
SqlCommand cmd = new SqlCommand("Update_Membtype", myConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mem_typeId", memid);
cmd.Parameters.AddWithValue("#membertype_name", membtype);
cmd.Parameters.AddWithValue("#dsc_rate", dsrate);
cmd.ExecuteNonQuery();
chk = true;
}
catch (Exception err)
{
chk = false;
}
return chk;
}
When I try to update data , it doesn't change nothing. Variable has its original values. Does not change to new data in text boxes. How can I fix these error.Please...

How do I create a limit of logins on my login screen?

I am currently trying to design an atm machine in C# and I am quite new to this.
I would like my login screen to Return back to my welcome screen after 3 failed attempt's at trying to login but I do not know where to start and how to implement my code into my program to do this.
My current code is as follows for my login screen:
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 System.Data.OleDb;
using System.Data.Common;
namespace bankkk
{
public partial class FrmLogin : Form
{
public FrmLogin()
{
InitializeComponent();
}
public static OleDbConnection con = new OleDbConnection();
string dbProvider;
string dbSource;
OleDbDataAdapter da;
public static DataSet ds1 = new DataSet();
string sql;
string pin;
int rownum = 0;
bool valid = false;
private void FrmLogin_Load(object sender, EventArgs e)
{
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;";
dbSource = "Data Source = 'd:\\bank11.accdb'";
con.ConnectionString = dbProvider + dbSource;
ds1 = new DataSet();
con.Open();
sql = " SELECT tblCustomers.* FROM tblCustomers";
da = new OleDbDataAdapter(sql, con);
rownum = da.Fill(ds1, "tblCustomers");
con.Close();
}
private void btnexit_Click(object sender, EventArgs e)
{
System.Environment.Exit(0);
this.Close();
}
//METHOD VALIDATE
private bool validate()
{
ds1 = new DataSet();
con.Open();
sql = "SELECT tblCustomers.* FROM tblCustomers WHERE ((tblCustomers.AccountNo) = '" + txtAccount.Text + "')";
da = new OleDbDataAdapter(sql, con);
rownum = da.Fill(ds1, "tblCustomers");
con.Close();
if (rownum != 1)
{
MessageBox.Show("Not a valid Account");
return false;
}
else
{
pin = ds1.Tables["tblCustomers"].Rows[0][4].ToString();
if (pin == txtPin.Text)
{
return true;
}
else
{
MessageBox.Show("INVALID PIN");
return false;
}
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
valid = validate();
if (valid == true)
{
if (txtAccount.Text == "11111111" && txtPin.Text == "9999")
{
Frmmanager Manager = new Frmmanager();
this.Close();
Manager.Show();
}
else
{
frmaccount account = new frmaccount();
this.Close();
account.Show();
{
txtAccount.Clear();
txtPin.Clear();
}
}
}
}
private void btnlogin_Click_1(object sender, EventArgs e)
{
valid = validate();
if (valid == true)
{
if (txtAccount.Text == "11111111" && txtPin.Text == "9999")
{
Frmmanager Manager = new Frmmanager();
this.Close();
Manager.Show();
}
else
{
frmaccount account = new frmaccount();
this.Close();
account.Show();
{
txtAccount.Clear();
txtPin.Clear();
}
}
}
}
}
}
You're saying Return back to my welcome screen, so I'll suppose that you are showing the FrmLogin using .ShowDialog() instead of .Show(). That way, you just need to close your old form.
If you are just doing .Show(), you can do something like this:
public partial class FrmWelcome {
//in some part of your code...
var frmLogin = new FrmLogin();
//when the login form is closed, show this one.
//Depending on your application, you might want to add some boolean variable
//to the Login Form that will be true if the user authentication failed, and
//show this form again only if it is true.
frmLogin.Closed += (s, e) => this.Show();
this.Hide();
frmLogin.Show();
}
Try the below code. The idea is to have a failedAttempts variable, which will be incremented everytime your validation code fails. When it is equals to 3, you just close the form (see above).
namespace bankkk
{
public partial class FrmLogin : Form
{
public FrmLogin()
{
InitializeComponent();
}
...
int failedAttempts = 0;
private void btnlogin_Click_1(object sender, EventArgs e)
{
valid = validate();
if (!valid) {
//Increment the number of failed attempts
failedAttempts += 1;
//If equal to 3
if (failedAttempts == 3) {
//Just close this window
this.Close();
}
}
else
{
//the same code you were using...
}
}
}
}
You can add a variable to your program and increment it to limit the number of attempts to login at all. To limit the number of attempts for an account add a table to store login information, including invalid attempts, to your database. Link that table to your Customer table. When an invalid attempt is made to login to a valid customer account increment the number of invalid attempts and write it back to the login table. On a successful login you can set the number of invalid attempts to 0.

How can i check for text identical in textBox while typing inside the textBox?

I have this Form:
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;
namespace GatherLinks
{
public partial class ChangeLink : Form
{
public ChangeLink()
{
InitializeComponent();
}
public string getText()
{
return textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
DialogResult = DialogResult.OK;
}
else
{
}
}
private void ChangeLink_Load(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
}
}
And this code in Form1:
public void KeysValuesUpdate()
{
DialogResult dr = DialogResult.None;
using (var w = new StreamWriter(keywords_path_file))
{
crawlLocaly1 = new CrawlLocaly(this);
crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
if (FormIsClosing != true)
{
dr = crawlLocaly1.ShowDialog(this);
}
if (dr == DialogResult.OK)
{
if (LocalyKeyWords.ContainsKey(mainUrl))
{
LocalyKeyWords[mainUrl].Clear();
LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
}
else
{
LocalyKeyWords[mainUrl] = new List<string>();
LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
}
Write(w);
ClearListBox();
}
if (dr == DialogResult.Cancel)
{
Write(w);
}
if (dr == DialogResult.None)
{
Write(w);
}
}
}
This KeysValuesUpdate() function is called here:
private void button2_Click(object sender, EventArgs e)
{
cl = new ChangeLink();
cl.StartPosition = FormStartPosition.CenterParent;
DialogResult dr = cl.ShowDialog(this);
if (dr == DialogResult.Cancel)
{
cl.Close();
}
else if (dr == DialogResult.OK)
{
label4.Text = cl.getText();
mainUrl = cl.getText();
if (!LocalyKeyWords.ContainsKey(mainUrl))
{
newUrl = true;
KeysValuesUpdate();
}
else
{
newUrl = false;
KeysValuesUpdate();
}
OptionsDB.set_changeWebSite(cl.getText());
cl.Close();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
When I click the button2 it's opening the new Form with a textbox and then inside I can type text.
Then I checking if the text inside already exist then newUrl is false or true.
Then when I click OK the OK button in the new Form then it's checking if the text I typed Contain/exist already or not.
I want that when the user type something in the textbox while he is typing if it's Contain/Exist the key then color the text in the textbox in Red one the user is keep typing and the text is not Contain/EXist color it back to Black but each time if the text in the textbox Contain/Exist already color it in Red and only if it's match case not if the text is inside other text:
This is in black:
For example : Danny hello all
But if I type in the textbox only: hello
Then the word hello will be in Red then if I kept typing after the hello then all the text in the textbox is Black if I delete the text and kept only the word hello then it will be Red again.
And that should be according to the code above and in realtime when im typing text in the textbox.
The new Form again with updated code with the textBox1 text changed event:
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;
namespace GatherLinks
{
public partial class ChangeLink : Form
{
Form1 f1;
public ChangeLink(Form1 f)
{
InitializeComponent();
f1 = f;
}
public string getText()
{
return textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
DialogResult = DialogResult.OK;
}
else
{
}
}
private void ChangeLink_Load(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (f1.mainUrl.Contains(textBox1.Text))
{
textBox1.ForeColor = Color.Red;
}
else
textBox1.ForeColor = Color.Black;
}
}
}
private void textBox_TextChanged(object sender, EventArgs e)
{
if (Regex.IsMatch(yourtext, #"\b" + textBox.Text + #"\b"))
{
textBox.ForeColor = Color.Red;
}
else
textBox.ForeColor = Color.Black;
}
Place your data containing variable name at the place of yourtext.
I have edited the answer. It is perfectly matching the whole words as you asked to do. To use Regex class, include System.Text.RegularExpressions namesapce.
You can implement textBox1 TextChanged event handler simply by defining a method
private void textBox1_TextChanged(object sender, EventArgs e)
{
var textBox = sender as TextBox;
String text = textBox.Text;
if (SomeCheck(text))
{
textBox.ForeColor = Color.Red;
}
else
{
textBox.ForeColor = Color.Black;
}
}
and assigning method textBox1_TextChanged to OnTextChanged property of textBox

Categories

Resources