I have a field named country in Invoice.aspx form. I have the below code.
invoice.aspx
<asp:DropDownList ID="lstCountryy" runat="server" Width="216px" Height="27px" AutoPostback="false">
</asp:DropDownList>
invoice.aspx.cs
lstCountryy.SelectedValue = dtInquiry.Rows[0]["country"].ToString();
Page load:
protected void Page_Load(object sender, EventArgs e)
{
txtTotal.Attributes.Add("readonly", "readonly");
txtvatt.Attributes.Add("readonly", "readonly");//added by chetan
txtDiscount.Attributes.Add("readonly", "readonly");//added by chetan
txtAmountInWords.Attributes.Add("readonly", "readonly");
if (!IsPostBack)
{
loadInvoiceDetails();
//SetAllCountries();//added by chetan
if (lstCountryy.SelectedValue == "U.A.E" || lstCountryy.SelectedValue == "BAHRAIN" || lstCountryy.SelectedValue == "SAUDI ARABIA")
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "float");
trdeclaration.Visible = false;
//txtvat.Enabled = true;
}
else
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "none");
trdeclaration.Visible = true;
}
}
}
Bind dropdownlist:
protected void SetAllCountries()
{
try
{
string queryStrUserType = "SELECT country_id,country_name FROM crm_countries";
ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
DataTable dt = clsDtResult.GetDataTable(queryStrUserType);
lstCountryy.DataSource = dt;
lstCountryy.DataValueField = "country_id";
lstCountryy.DataTextField = "country_name";
lstCountryy.DataBind();
lstCountryy.Items.Insert(0, "--Select--");
}
catch (Exception Ex)
{
}
}
dtInquiry is my Inquiry table in which country field is there and I am fetching the value from inquiry form to invoice form. I am not getting the selected value; it shows blank (""). I don't know what's wrong with that. I am a beginner in C#.
I was not getting the selected value.It should be like this: SetAllCountries Should be first and then loadinvoicedetails.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetAllCountries();
loadInvoiceDetails();
.....
.....
}
}
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 new to asp.net and needs some help. I have a gridview with paging for every 20 records per page, I have a search button outside the gridview. What I need to do is when I click the search button, the results must be bind to gridview(which is happening now), however when the records are more than the pagesize and I need to go to the next page of the grid, the binding is lost and the binded records are the ones form the page on load event. below is my code sample.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void BindData()
{
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//SaveSelectedValues();
gvwAssociation.PageIndex = e.NewPageIndex;
//BindData();
//PopulateSelectedValues();
}
First of all you should have the following event handler for paging
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
Then, move your search/ filter logic within the search button to a private method (say "bindGridWithFilter")
TIP: Try to combine both BindData and bindGridWithFilter so when there's no filter you display all records
UPDATE
Here's some refactored code for you to get an idea what I meant above.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridWithFilter();
}
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
bindGridWithFilter();
}
private void bindGridWithFilter()
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
// If you don't have a filter you show all records
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
else
{
// This is same as the logic in your search button
// display only the filtered records
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
List<EventFile> fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
}
This should work.
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));
I'm have problemas to work with Session in my project ASp.NEt c# in IE9.
Sometimes occured error:
"Object reference not set to an instance of as object"
Other problem is that in IE9, sometimes not save my Session to change Idiom to others pages.
In Chrome all works good!
Below is my Page_Load and CarregaGrid(). This problem occured in sometimes, no all time, and in any page no in all page or just in one specific page.
public void CarregaGrid()
{
var listByGroupM = new ManageUsers().ConsultUsersGroupM();
if (listByGroupM != null)
{
this.GridView1.DataSource = listByGroupM;
if (listByGroupM.Count != 0)
{
this.GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
if (divModify.Visible == true)
{
foreach (GridViewRow row in GridView1.Rows)
{
string idioma = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToString();
if (Session["idioma"].ToString() != null)
{
idioma = Session["idioma"].ToString();
}
Idioma.MudaCultura(idioma);
Button btnDelete = (Button)row.FindControl("btnDelete");
btnDelete.Text = Idioma.RetornaMensagem("btnDelete");
string UserName = row.Cells[1].Text;
PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "x.com", "x", "xxx");
UserPrincipal insUserPrincipal = UserPrincipal.FindByIdentity(insPrincipalContext, UserName);
if (insUserPrincipal == null)
{
row.Cells[2].Text = "";
row.Cells[3].Text = "";
}
else
{
string Email = insUserPrincipal.EmailAddress;
row.Cells[2].Text = Email;
string DisplayName = insUserPrincipal.DisplayName;
row.Cells[3].Text = DisplayName;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string idioma = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToString();
if (Session["idioma"].ToString() != null)
{
idioma = Session["idioma"].ToString();
}
Idioma.MudaCultura(idioma);
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
}
}
protected void pt_OnChange(object sender, EventArgs e)
{
Idioma.MudaCultura("pt");
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
Session["idioma"] = "pt";
}
protected void en_OnChange(object sender, EventArgs e)
{
Idioma.MudaCultura("en");
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
Session["idioma"] = "en";
}
protected void es_OnChange(object sender, EventArgs e)
{
Idioma.MudaCultura("es");
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
Session["idioma"] = "es";
}
replace
if (Session["idioma"].ToString() != null)
with
if (Session["idioma"] != null)
If the session object is NULL, then calling .ToString() will throw an error.
Change:
if (Session["idioma"].ToString() != null)
to:
if (Session["idioma"] != null)
I am trying to clear two text fields after the data is posted. The page posts back but does not delete the text fields.
txtComment.Text = "";
txtEmail.Text = "";
How can I fix my code below.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["PicID"] != null)
{
int vPicID = Convert.ToInt32(Request.QueryString["PicID"]);
BSComments DTGetComments = new BSComments();
DataTable DTGetCommentsbyID = DTGetComments.GetCommentsByPicIDs(vPicID);
//Create User object
// GetMemberInfo GetMember = new GetMemberInfo();
// DataTable DAMemberInfo = GetMember.GetmemberInfo(UserID);
txtComment.Text = "";
txtEmail.Text = "";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//Check to see if the Email has an account
BSComments CheckIFmember = new BSComments();
DataTable DAMemberInfo = CheckIFmember.CheckIFMemberReturnNameEmail(txtEmail.Text);
int picid =Convert.ToInt32(Request.QueryString["PicID"]);
if (DAMemberInfo.Rows.Count > 0)
{
String myGuid = "";
String MemberName = "";
foreach (DataRow row in DAMemberInfo.Rows)
{
myGuid = row["Guid"].ToString();
MemberName = row["MemberName"].ToString();
}
BSComments InstertComments = new BSComments();
InstertComments.InserComment(picid, txtEmail.Text, txtComment.Text, MemberName, myGuid);
txtComment.Text = "";
txtEmail.Text = "";
}
else
{
txtComment.Text = "You need to have an account to post.";
}
txtComment.Text = "";
txtEmail.Text = "";
}
}
If you have stepped through your code to determine that the txtComment and txtEmail fields have actually had their .Text values set to String.Empty, then I'd suggest the problem may not be in your code at all.
Look to see if the browser is "helpfully" prefilling those fields for you. If so, you can add an attribute in your aspx file on those controls for AutoComplete="off"
For example:
<asp:TextBox runat="server" id="txtComment" AutoComplete="off" />