I am creating an alert and trying to call a click event through javascript function when "OK" of alert is pressed.It runs pretty well if I create the alert on rpage_Load but When I crate the alert on clicking of a buttton, then on pressing "OK" of alert the required click event is not called.
This is how I create the alert
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Startup", "Test();", true);
}
This is the javascript function which calls a click event
<script type="text/javascript">
function Test() {
alert('There is no Bookmarked Question Available');
document.getElementById('btnReview').click();
}
</script>
This is the click event which will be called through Test()
protected void btnReview_Click(object sender, EventArgs e)
{
count = int.Parse((string)ViewState["S.NO"]);
dt1 = (DataTable)ViewState["Question"];
if (rbOption.SelectedValue != "")
{
string strUserOpt = rbOption.SelectedItem.Text;
strUserOpt = strUserOpt.Substring(20);
dt1.Rows[count - 1][9] = strUserOpt;
dt1.Rows[count - 1][10] = rbOption.SelectedValue;
}
lblReview.Visible = true;
tblQues.Visible = false;
tblReview.Visible = true;
btnBookMark.Text = "Bookmark";
btnBookMark.Font.Bold = false;
btnBookMark.BackColor = Color.Empty;
lblQuestionNo.Visible = false;
lblTopic.Visible = false;
lblTestHead.Visible = false;
DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Status");
dt.Columns.Add("BookMarked");
DataRow dr1;
foreach (DataRow dr in dt1.Rows)
{
dr1 = dt.NewRow();
dr1[0] = dr[0].ToString() ;
if (dr[9].ToString() != "") { dr1[1] = "Attempted"; } else { dr1[1] = "Un-attempted"; }
if (dr[11].ToString() != "") { dr1[2] = "Yes"; } else { dr1[2] = "No"; }
dt.Rows.Add(dr1);
}
dt.AcceptChanges();
ClsDataBind.DoGridViewBind(grdReview, dt, _errMsg);
btnBookMark.Visible = false;
btnNext.Visible = false;
btnPrevious.Visible = false;
btnReview.Visible = false;
}
The main problem may be you are clicking Button1 after btnReview because under btnReview_Click
this happens
btnReview.Visible = false;
This means you will not be able to use Button1_Click event unless
btnReview.Visible = true;
Related
I have spent some time designing my first project using C#, it is a Windows form project with 8 buttons on the side. pressing one of the buttons will open another form within the parent form as a window. On clicking the button the new form loads up about 27 objects mostly Labels, Textboxes, Comboboxes and a few DateTimePickers. For some reason it you can see it drawing the boxes and it looks slow. I have an SQL db included with my project which is tiny and contains only 2 rows of data. It is very dishearting to spend all that time working on it only to see it run like a ZX Spectrum. I am using Microsoft Visual Studio 2019 and is fully updated. I have no errors, no warnings thank god but the performance is horrible. One of the comboBoxes when selected will make visible 3 more textBoxes and even making those visible is really slow. Is there something I am doing wrong or is there a way to have it working faster please?
This is the code of my childForm which opens from the main parentForm, sorry is is a bit long but it is all of it.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace AvianManager.Forms
{
public partial class formMyBirds : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Dion\Documents\AvianManager.mdf;Integrated Security=True;Connect Timeout=30");
public formMyBirds()
{
InitializeComponent();
}
private void formMyBirds_Load(object sender, EventArgs e)
{
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
var form = Application.OpenForms["formMyBirdsHelper"]; // Lookup form and check if already open
if (form == null)
{
formMyBirdsHelper MyBirdsHelper = new formMyBirdsHelper(); // Instantiate a FormMyBirdsHelp object.
MyBirdsHelper.Show(); // Show FormMyBirdsHelp and
}
}
private void comboBoxLegBandType_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxLegBandType.GetItemText(this.comboBoxLegBandType.SelectedItem);
if (selected != "None" || selected == null)
{
textBoxLegBandID.Visible = true;
labelLegBandId.Visible = true;
textBoxLegBandSize.Visible = true;
labelLegBandSize.Visible = true;
}
else
{
textBoxLegBandID.Visible = false;
labelLegBandId.Visible = false;
textBoxLegBandSize.Visible = false;
labelLegBandSize.Visible = false;
}
}
private void comboBoxPrevOwner_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxPrevOwner.GetItemText(this.comboBoxPrevOwner.SelectedItem);
if (selected != "No")
{
textBoxLastOwnerName.Visible = true;
labelLastOwnerName.Visible = true;
textBoxLastOwnerFone.Visible = true;
labelLastOwnerFone.Visible = true;
textBoxLastOwnerAddr.Visible = true;
labelLastOwnerAddr.Visible = true;
}
else
{
textBoxLastOwnerName.Visible = false;
labelLastOwnerName.Visible = false;
textBoxLastOwnerFone.Visible = false;
labelLastOwnerFone.Visible = false;
textBoxLastOwnerAddr.Visible = false;
labelLastOwnerAddr.Visible = false;
}
}
private void comboBoxVitalStatus_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxVitalStatus.GetItemText(this.comboBoxVitalStatus.SelectedItem);
if (selected != "Alive")
{
dateTimeDateOfDeath.Visible = true;
labelDateOfDeath.Visible = true;
textBoxCauseOfDeath.Visible = true;
labelCauseOfDeath.Visible = true;
}
else
{
dateTimeDateOfDeath.Visible = false;
labelDateOfDeath.Visible = false;
textBoxCauseOfDeath.Visible = false;
labelCauseOfDeath.Visible = false;
}
}
private void comboBoxRetained_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxRetained.GetItemText(this.comboBoxRetained.SelectedItem);
if (selected != "Yes")
{
dateTimeRelinquishedDate.Visible = true;
labelRelinquishedDate.Visible = true;
}
else
{
dateTimeRelinquishedDate.Visible = false;
labelRelinquishedDate.Visible = false;
}
}
private void textBoxUid_TextChanged(object sender, EventArgs e)
{
SqlCommand cmd1 = new SqlCommand("select top 1 * from dbMyBirds where db_Uid = '" + textBoxUid.Text + "'", connection);
cmd1.Parameters.AddWithValue("db_Uid", textBoxUid.Text);
SqlDataReader reader1;
connection.Open();
reader1 = cmd1.ExecuteReader();
if (reader1.Read())
{
labelResult.Text = "Found";
textBoxName.Text = reader1["db_Name"].ToString();
textBoxSpecies.Text = reader1["db_Species"].ToString();
comboBoxLegBandType.Text = reader1["db_LegBandType"].ToString();
textBoxLegBandID.Text = reader1["db_LegBandId"].ToString();
textBoxLegBandSize.Text = reader1["db_LegBandSize"].ToString();
comboBoxPrevOwner.Text = reader1["db_PrevOwner"].ToString();
textBoxLastOwnerName.Text = reader1["db_PrevOwnerName"].ToString();
textBoxLastOwnerFone.Text = reader1["db_PrevOwnerFone"].ToString();
textBoxLastOwnerAddr.Text = reader1["db_PrevOwnerAddr"].ToString();
comboBoxIsHybrid.Text = reader1["db_Hybrid"].ToString();
comboBoxRearedBy.Text = reader1["db_RearedBy"].ToString();
textBoxDisformaties.Text = reader1["db_Disformaties"].ToString();
comboBoxVitalStatus.Text = reader1["db_VitalStatus"].ToString();
dateTimeDateOfDeath.Text = reader1["db_DateDied"].ToString();
textBoxCauseOfDeath.Text = reader1["db_CauseOfDeath"].ToString();
comboBoxRetained.Text = reader1["db_Retained"].ToString();
dateTimeRelinquishedDate.Text = reader1["db_RelinquishedDate"].ToString();
dateTimeHatchDate.Text = reader1["db_HatchDate"].ToString();
dateTimeFledgeDate.Text = reader1["db_FledgeDate"].ToString();
comboBoxMaleParentHybrid.Text = reader1["db_MPisHybrid"].ToString();
textBoxMaleParentId.Text = reader1["db_MPUid"].ToString();
textBoxMaleParentSpecies.Text = reader1["db_MPSpecies"].ToString();
comboBoxHenParentHybrid.Text = reader1["db_FPisHybrid"].ToString();
textBoxHenParentId.Text = reader1["db_FPUid"].ToString();
textBoxHenParentSpecies.Text = reader1["db_FPSpecies"].ToString();
textBoxNotes.Text = reader1["db_Notes"].ToString();
}
else
{
resetInputs();
if (textBoxUid.Text == "")
{
labelResult.Text = "Live Search";
}
else
{
labelResult.Text = "Nothing Found";
}
}
connection.Close();
}
//Reset input fields if no results
private void resetInputs()
{
string dt2;
DateTime date2 = DateTime.Now;
dt2 = date2.ToShortDateString(); // display format: 15/07/2021
textBoxName.Text = "";
textBoxSpecies.Text = "";
comboBoxLegBandType.Text = "Select";
textBoxLegBandID.Text = "";
textBoxLegBandSize.Text = "";
comboBoxPrevOwner.Text = "Select";
textBoxLastOwnerName.Text = "";
textBoxLastOwnerFone.Text = "";
textBoxLastOwnerAddr.Text = "";
comboBoxIsHybrid.Text = "Select";
comboBoxRearedBy.Text = "Select";
textBoxDisformaties.Text = "";
comboBoxVitalStatus.Text = "Select";
dateTimeDateOfDeath.Text = dt2;
textBoxCauseOfDeath.Text = "";
comboBoxRetained.Text = "Select";
dateTimeRelinquishedDate.Text = dt2;
dateTimeHatchDate.Text = dt2;
dateTimeFledgeDate.Text = dt2;
comboBoxMaleParentHybrid.Text = "Select";
textBoxMaleParentId.Text = "";
textBoxMaleParentSpecies.Text = "";
comboBoxHenParentHybrid.Text = "Select";
textBoxHenParentId.Text = "";
textBoxHenParentSpecies.Text = "";
textBoxNotes.Text = "";
}
private void buttonInsert_Click(object sender, EventArgs e)
{
}
}
}
I'm setting datagridview as object and show in windows form in Textbox change event. When open form and start texting into textbox then datagridview is show but when text is empty or null datagridview continue been visible. How can I accomplish datagridview invisible in windows form?
This is for C#. I have tried to dispose datagridview in if clause but it didn't work.
Here is my code:
public class CreateDataGridView
{
public DataGridView clientsDgv = new DataGridView();
public CreateDataGridView()
{
clientsDgv.ReadOnly = true;
clientsDgv.Name = "clientsDgv";
clientsDgv.AllowUserToAddRows = false;
clientsDgv.AllowUserToDeleteRows = false;
clientsDgv.AllowUserToResizeRows = false;
}
public DataGridView Createdgv()
{
return clientsDgv;
}
Here is my code in windows form.
//Get datagridview in windows form textbox change event
private void TxtID_TextChanged(object sender, EventArgs e)
{
switch (this.cmbSelectAction.SelectedIndex)
{
case 1:
CreateDataGridView clientsdgv = new CreateDataGridView();
//clientsdgv.clientsDgv
Controls.Add(clientsdgv.clientsDgv);
clientsdgv.clientsDgv.BringToFront();
DesignDataGridView designdgv = new DesignDataGridView();
designdgv.ClientsDataGridFormatting(clientsdgv.clientsDgv);
designdgv.ClientsDataGridPosition(clientsdgv.clientsDgv, txtID);
//SetDoubleBuffered.SetDoubleBuffering(clientsdgv.clientsDgv, true);
if (string.IsNullOrEmpty(txtID.Text) || txtID.Text == "0")
{
clientsdgv.clientsDgv.DataSource = null;
clientsdgv.clientsDgv.Update();
clientsdgv.clientsDgv.Dispose();
clientsdgv.clientsDgv.Visible = false;
return;
}
else
{
GetSqlData getSqlData = new GetSqlData();
try
{
clientsdgv.clientsDgv.SuspendLayout();
columnName = "PersonalIDBulstat";
ID = txtID.Text;
clientsdgv.clientsDgv.Visible = true;
clientsdgv.clientsDgv.DataSource = getSqlData.SearchClientsInSql(columnName, ID);
clientsdgv.clientsDgv.Update();
clientsdgv.clientsDgv.ResumeLayout();
}
catch
{
title = "Clients";
SetMessageBoxTypes.MessageBoxContactAdminOk(title);
}
}
break;
}
}
Thank you in advance!
It is my working code when form is load where dgvClients is declare as DataGridView:
private void Clients_Load(object sender, EventArgs e)
{
CreateDataGridView clientsdgv = new CreateDataGridView();
dgvClients = clientsdgv.dgvClients;
}
private void TxtID_TextChanged(object sender, EventArgs e)
{
switch (this.cmbSelectAction.SelectedIndex)
{
case 1:
Controls.Add(dgvClients);
dgvClients.BringToFront();
DesignDataGridView designdgv = new DesignDataGridView();
designdgv.ClientsDataGridPosition(dgvClients, this.txtID);
GetSqlData getSqlData = new GetSqlData();
if (string.IsNullOrEmpty(txtID.Text) || txtID.Text == "0")
{
dgvClients.DataSource = null;
dgvClients.Update();
dgvClients.Visible = false;
return;
}
else
{
try
{
dgvClients.SuspendLayout();
columnName = "PersonalIDBulstat";
ID = txtID.Text;
dgvClients.Visible = true;
dgvClients.DataSource = getSqlData.SearchClientsInSql(columnName, ID);
dgvClients.Update();
dgvClients.ResumeLayout();
}
catch
{
title = "Clients";
SetMessageBoxTypes.MessageBoxContactAdminOk(title);
}
}
break;
}
}
I have a MetroFramework.Controls.MetroGrid in my windows forms application. In frmPatientList_Shown I call a method loadPatientList(). I also add a DataGridViewLinkColumn after binding the dtb to the gridview.
Clicking the link opens a new form where I update Patient data, and on formEditPatient.FormClosed I call the loadPatientList() method again, This time the DataGridViewLinkColumn is being added twice. How can I prevent to Add the link twice ?
Here is my code:
private void frmPatientList_Shown(object sender, EventArgs e)
{
loadPatientList();
}
private void loadPatientList()
{
DataTable dtb = Patient.getPatientList();
bindToGrid(dtb);
}
private void bindToGrid(DataTable dtb)
{
dataGridView1.DataSource = null;
using (dtb)
{
dataGridView1.DataSource = dtb;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns[0].Name = "PatientId";
dataGridView1.Columns[0].HeaderText = "ID";
dataGridView1.Columns[0].DataPropertyName = "PatientId";
// more code here.
}
DataGridViewLinkColumn EditLink = new DataGridViewLinkColumn();
EditLink.UseColumnTextForLinkValue = true;
EditLink.HeaderText = " Edit ";
EditLink.DataPropertyName = "lnkColumn";
EditLink.LinkBehavior = LinkBehavior.SystemDefault;
EditLink.Text = "Edit";
dataGridView1.Columns.Add(EditLink);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 8 && e.RowIndex >= 0)
{
using (frmEditPatient formEditPatient = new frmEditPatient(id))
{
formEditPatient.FormClosed += FormEditPatient_FormClosed;
formEditPatient.ShowDialog();
}
}
}
private void FormEditPatient_FormClosed(object sender, FormClosedEventArgs e)
{
loadPatientList();
}
Any help would be appreciated.
You check if the column exist,
bool hasEditColumn = false;
foreach (DataGridViewColumn item in dataGridView1.Columns)
{
if (item.GetType() == typeof(DataGridViewLinkColumn) && item.HeaderText == "Edit")
{
hasEditColumn = true;
break;
}
}
if (!hasEditColumn)
{
DataGridViewLinkColumn EditLink = new DataGridViewLinkColumn();
EditLink.UseColumnTextForLinkValue = true;
EditLink.HeaderText = "Edit";
EditLink.DataPropertyName = "lnkColumn";
EditLink.LinkBehavior = LinkBehavior.SystemDefault;
EditLink.Text = "Edit";
dataGridView1.Columns.Add(EditLink);
dataGridView1.Refresh();
}
In frmPatientList_Shown function you add the link
private void frmPatientList_Shown(object sender, EventArgs e)
{
DataGridViewLinkColumn EditLink = new DataGridViewLinkColumn();
EditLink.UseColumnTextForLinkValue = true;
EditLink.HeaderText = " Edit ";
EditLink.DataPropertyName = "lnkColumn";
EditLink.LinkBehavior = LinkBehavior.SystemDefault;
EditLink.Text = "Edit";
dataGridView1.Columns.Add(EditLink);
loadPatientList();
}
In bindToGrid function you do not add the link
private void bindToGrid(DataTable dtb)
{
dataGridView1.DataSource = null;
using (dtb)
{
dataGridView1.DataSource = dtb;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns[0].Name = "PatientId";
dataGridView1.Columns[0].HeaderText = "ID";
dataGridView1.Columns[0].DataPropertyName = "PatientId";
// more code here.
}
//DataGridViewLinkColumn EditLink = new DataGridViewLinkColumn();
//EditLink.UseColumnTextForLinkValue = true;
//EditLink.HeaderText = " Edit ";
//EditLink.DataPropertyName = "lnkColumn";
//EditLink.LinkBehavior = LinkBehavior.SystemDefault;
//EditLink.Text = "Edit";
//dataGridView1.Columns.Add(EditLink);
}
I hope it will help you.
ASP.Net code:
<asp:DropDownList ID="ddlKid" runat="server" AutoPostBack="true" CssClass="ddlReports"
Width="160px" OnSelectedIndexChanged="ddlKid_SelectedIndexChanged">
</asp:DropDownList>
C# code:
protected void ddlKid_SelectedIndexChanged(object sender, EventArgs e)
{
int i = ddlKid.SelectedIndex;
count = i;
int KidId = int.Parse(KidArray[i].ToString());
ArrayList ADA = new ArrayList();
ADA.Add(FirstAssignment.SelectedItem);
ADA.Add(SecondAssignment.SelectedItem);
DrawTableNew(ADA, KidId);
}
protected void Page_Load(object sender, EventArgs e)
{
GameLib.Reports.ReportID = 6;
if (!IsPostBack)
{
FillGrades();
FillKids();
count = 0;
Label1.Visible = false;
FirstAssignment.Visible = false;
SecondAssignment.Visible = false;
L1st.Visible = false;
L2nd.Visible = false;
Header.Visible = false;
Label2.Visible = false;
Div2.Visible = false;
Panel1.Visible = false;
DwdTable.Visible = false;
DwdButton2.Visible = false;
pnlIssues.Visible = false;
Panel2.Visible = false;
}
else
{
FillGrades();
// FillKids();
}
}
protected void FillKids()
{
ddlKid.Visible = true;
try
{
if (GameUser.UserType == 1)
{
ddlKid.Items.Insert(0, new System.Web.UI.WebControls.ListItem(GameUser.UserName, GameUser.UserID.ToString()));
}
else
{
DataTable dt = new DataTable();
//dt = GameLib.GameUser.GetKidsForParent(GameUser.UserID);
dt = GameLib.GameUser.GetKidsForParentAsPerGrade(GameUser.UserID, ddlAssessment.SelectedItem.ToString());
for (int i = 0; i < dt.Rows.Count; i++)
{
int kidId = (int)dt.Rows[i]["intUserID"];
KidArray.Add(kidId);
}
if (dt.Rows.Count <= 0)
{
//MPEGrade.Show();
}
else
{
ddlKid.DataSource = dt;
ddlKid.DataTextField = "vchLoginName";
ddlKid.DataValueField = "vchGradeName";
ddlKid.DataBind();
}
}
}
catch
{
}
}
The problem is my ddlKid_SelectedIndexChanged is not executing. After page load it stops at else statement. Its code for fill kids(Adding drop down data).
The fill kid only called on the first that is !postback.
you can change binding value:
fill kids value like:
string vchLoginName=//login name from db;
string vchGradeName=//Grade name from db;
ddlKid.Items.Add(new ListItem(vchLoginName,vchGradeName));
//my problem is when i fire SelectedIndexChanged event of ddlmodalitylist asynchronously(ajax call) then javascript load event is not fired..thats y i have to fire onload event from server side.
window.onload = body_Onload;
function body_Onload() {
//javascript code
}
protected void ddlModalityList_SelectedIndexChanged(object sender, EventArgs e)
{
ddlStudy.Items.Clear();
ListItem selectedPair = ddlModalityList.SelectedItem;
string str= selectedPair.Value;
int ID= Convert.ToInt32(str);
if (ID == -1)
{
// ddlStudy.Items.Clear();
return;
}
DataTable dataTableStudy = null;
dataTableStudy = objSqlDbComm.ExecuteDatasetQuery(strSQL).Tables[0];
var dictioneryStudy = new Dictionary<int, string>();
foreach (DataRow dr in dataTableStudy.Rows)
{
dictioneryStudy.Add(Convert.ToInt32(dr["Study_ID"]), dr["Study_Desc"].ToString());
}
ddlStudy.DataTextField = "Value";
ddlStudy.DataValueField = "Key";
ddlStudy.DataSource = dictioneryStudy;
ddlStudy.DataBind();
ddlStudy.Items.Insert(0, new ListItem("[Select]", "-1"));
ddlStudy.Items[0].Selected = true;
}
Sys.Application.add_init(your_bodyload_function);