List Box Selected.value throwing null exception - c#

Populated list box like this:
if (ds != null)
{
ListPreviousRecords.Items.Clear();
ListPreviousRecords.DataSource = ds;
ListPreviousRecords.DataTextField = "Date";
ListPreviousRecords.DataValueField = "ID";
ListPreviousRecords.DataBind();
}
Get selected value:
protected void ListPreviousRecords_OnSelectedIndexChanged(object sender, EventArgs e)
{
if(ListPreviousRecords.SelectedItem.Value != "")
{
int mySelectedValue = int.Parse(ListPreviousRecords.SelectedItem.Value);// throwing null exception
loadPreviousDetails(mySelectedValue);
}
}

You can add this code in order to ensure that not null value is entered
if(!string.IsNullOrEmpty(ListPreviousRecords.SelectedItem.Value ))
{
...
}
And Ensure that AutoPostBack="true" is set on your control
link : http://msdn.microsoft.com/fr-fr/library/system.string.isnullorempty.aspx

Change:
if(ListPreviousRecords.SelectedItem.Value != "")
To:
if (!string.IsNullOrEmpty(ListPreviousRecords.SelectedItem))

Use ListPreviousRecords.SelectedValue.
if (!string.IsNullOrWhiteSpace(ListPreviousRecords.SelectedValue)) {
// ...
}

Related

ASP.NET Formview Textbox value- Object reference not set to an instance of an object

I would like to know whether or not this control is null once the page loads before I perform another operation. At the moment it just throws the object reference error.
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.ReadOnly)
{
string cname =
(this.FormView1.FindControl("companyname") as
System.Web.UI.WebControls.TextBox).Text;
if (cname == null)
{
}
else{
}
}
}
check for textbox first (make sure thats the ID youre looking up), something like,
TextBox compName = (Textbox)this.FormView1.FindControl("companyname");
string cName = "";
if(compName != null)
{
cName = compName.Text;
}
else
{
// textbox not found! do something?
}

Edit row in GridView with DropDownList

I need edit the row of GridView in RowDataBound event.
If tried edit one row with field Area not null value I don't have problem, but if tried edit one row with field Area null or empty value I have the classic error :
Object reference not set to an instance of an object
On the line :
ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
I think that inserted in my code this condition resolve the problem but without success :
if (!string.IsNullOrEmpty(hdnval.Value))
{
ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
}
else
{
ddlCities.Items.FindByValue(hdnval.Value).Selected = false;
}
Please help me, thank you in advance.
My code below.
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvProducts.EditIndex == e.Row.RowIndex)
{
DropDownList ddlCities = (DropDownList)e.Row.FindControl("Area");
HiddenField hdnval = (HiddenField)e.Row.FindControl("hdnArea");
string query = " Select distinct Area from ... ; ";
OdbcCommand cmd = new OdbcCommand(query);
ddlCities.DataSource = GetData(cmd);
ddlCities.DataTextField = "Area";
ddlCities.DataValueField = "Area";
ddlCities.DataBind();
if (!string.IsNullOrEmpty(hdnval.Value))
{
ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
}
else
{
ddlCities.Items.FindByValue(hdnval.Value).Selected = false;
}
}
}
Please try :
if(ddlCities.Items.FindByValue(hdnval.Value) != null)
{
ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
}
I hope I have helped you.

How to use string.IsNullOrEmpty in Textbox?

I'm trying to display null value only if the textbox is empty. In my case even if i'm giving input in the textbox, it won't detect as null value. Kindly help me to solve my error please.
protected void AnyTextBox_TextChanged(object sender, EventArgs e)
{
if ((string.IsNullOrEmpty(TextBox1.Text)))
{
TBResult1.Text = "N/A";
}
else
{
TBResult1.Text = TextBox1.ToString();
}
<asp:TextBox ID="TextBox1" OnTextChanged="AnyTextBox_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
<asp:TextBox ID="TBResult1" OnTextChanged="AnyTextBox_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
From documentation:
String.IsNullOrEmpty Method
Indicates whether the specified string is null or an Empty string.
Example:
string s1 = "abcd"; // is neither null nor empty.
string s2 = ""; // is null or empty
string s3 = null; // is null or empty
string.IsNullOrWhiteSpace(s1); // returns false
string.IsNullOrWhiteSpace(s2); // returns true
string.IsNullOrWhiteSpace(s3); // returns true
Also, you can do this:
if (string.IsNullOrEmpty(s1)) {
Message.Show("The string s1 is null or empty.");
}
In your code:
if ((string.IsNullOrEmpty(TextBox1.Text)))
{
// The TextBox1 does NOT contain text
TBResult1.Text = "N/A";
}
else
{
// The TextBox1 DOES contain text
// TBResult1.Text = TextBox1.ToString();
// Use .Text instead of ToString();
TBResult1.Text = TextBox1.Text;
}
Replace
TBResult1.Text = TextBox1.ToString();
with
TBResult1.Text = TextBox1.Text;
Try this:
if(string.IsNullOrWhiteSpace(this.textBox1.Text))
{
MessageBox.Show("TextBox is empty");
}
It should be like this, You have missed TextBox1.Text in the else part
protected void AnyTextBox_TextChanged(object sender, EventArgs e)
{
if ((string.IsNullOrEmpty(TextBox1.Text)))
{
TBResult1.Text = "N/A";
}
else
{
TBResult1.Text = TextBox1.Text.ToString();
}
}
Check you conditions like this.i use this one and it works fine.
if(TextBox1.Text.Trim().Length > 0)
{
//Perform your logic here
}
Otherwise you have to check these two functions
if (string.IsNullOrEmpty(TextBox1.Text.Trim()) || string.IsNullOrWhiteSpace(TextBox1.Text.Trim()))
{
}

Handle PageIndexChanging event

I have a Query that runs when the user submits a search and the gridview is loaded.
I want to page the gridview and would usually have my grid in a LoadGrid(). I have the paging working ok and everything is good until I want to view page 2 of the GridView.
protected void btn_Search_Click(object sender, EventArgs e)
{
// Init()
// -----
pnl_Message.Visible = false;
lbl_message.Text = String.Empty;
// Clear grid of previous results
// ==============================
ResultsGridView.DataSource = null;
ResultsGridView.DataBind();
try
{
using (var db = new dbDataContext())
{
// Check Fields
// ------------
if (txt_CustomerName.Text == string.Empty && txt_CCNo.Text == string.Empty &&
txt_SwiftNo.Text == string.Empty && drp_Provider.SelectedValue == string.Empty)
{
lbl_message.Text += "* Please enter a search term";
pnl_Message.Visible = true;
pnl_Message.CssClass = "loginError";
pnl_results.Visible = false;
}
// Search Database
// ---------------
if (lbl_message.Text == String.Empty)
{
var customer = txt_CustomerName.Text.Length > 1 ? txt_CustomerName.Text.Trim() :
"Xcxcx";
//var provider = drp_Provider.SelectedItem.Text.Trim();
var concern = txt_CCNo.Text == "" ? 0 : Convert.ToInt32(txt_CCNo.Text);
var swiftid = txt_SwiftNo.Text == "" ? 0 : Convert.ToInt32(txt_SwiftNo.Text);
// Check which fields populated
// ----------------------------
var result =
from c in db.tbl_Concerns
where (c.ProviderId == Convert.ToInt32(drp_Provider.SelectedValue))
|| (c.person_Fullname.Contains(customer))
|| (c.SwiftId == swiftid)
|| (c.ConcernId == concern)
select new
{
c.ConcernId,
Swift = c.SwiftId,
FullName = c.person_Fullname,
Provider = c.tbl_Provider.provider_Name,
Concern_Detail = c.tbl_RaisedConcern.RaisedConcernText,
DateFrom = c.concern_DateFrom,
DateTo = c.concern_DateTo
};
// If No Results
// -------------
if (!result.Any())
{
lbl_message.Text += "* No results match your search, please try again.";
pnl_Message.Visible = true;
pnl_Message.CssClass = "loginError";
}
else
{
// Show Table
// ----------
pnl_results.Visible = true;
ResultsGridView.DataSource = result;
ResultsGridView.DataBind();
// Table Header Names
// ------------------
ResultsGridView.HeaderRow.Cells[0].Text = "Select";
}
}
}
}
catch (SystemException ex)
{
var exceptionUtility = new genericExceptions();
exceptionUtility.genericSystemException(
ex,
Server.MachineName,
Page.TemplateSourceDirectory.Remove(0, 1) + Page.AppRelativeVirtualPath.Remove(0, 1),
ConfigurationManager.AppSettings["emailSupport"],
ConfigurationManager.AppSettings["emailFrom"],
string.Empty);
}
}
My PageIndexChanging event I would usually call the loadGrid() but I do not have that situation. I have tried just adding ResultsGridView.DataBind() but get the error Sequence contains no elements.
protected void ResultsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
ResultsGridView.PageIndex = e.NewPageIndex;
** How Can I bind the Grid**
}
Try this..
session["somename"]=result;
protected void ResultsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
var somename=session["somename"].Tostring();
ResultsGridView.PageIndex = e.NewPageIndex;
ResultsGridview.Datasource=somename;
REsultsGridview.Databind();
}

Displaying multiple columns on LookupEdit of Devexpress

I have a DataSource bound to a LookUpEdit. For example I have 2 columns FirstName and LastName and I want to set DisplayMember property to these two columns.
I found that I should subscribe to lookUp_CustomDisplayText() and edit display text property like this:
private void lookUpCompanyPerson_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
{
LookUpEdit edit = sender as LookUpEdit;
if (e.DisplayText != "")
{
e.DisplayText = e.DisplayText + " " + (string)e.Value;
}
}
but I did not understand what e.Value is and I want to display another column for selected row, not the valuemember of selected row.
This is how I bind the datasource to lookupedit:
private void populateComboBoxForCompanyPerson()
{
lookUpCompanyPerson.Properties.ForceInitialize();
bs = new BindingSource(myDataSet, "CompanyPerson");
lookUpCompanyPerson.Properties.DataSource = bs;
lookUpCompanyPerson.Properties.DisplayMember = "CompanyName";
lookUpCompanyPerson.Properties.ValueMember = "PersonID";
this.lookUpCompanyPerson.Properties.Columns.Add(new LookUpColumnInfo("PersonID"));
this.lookUpCompanyPerson.Properties.Columns["PersonID"].Visible = false;
this.lookUpCompanyPerson.Properties.Columns.Add(new LookUpColumnInfo("FirstName"));
this.lookUpCompanyPerson.Properties.Columns.Add(new LookUpColumnInfo("LastName"));
this.lookUpCompanyPerson.Properties.Columns.Add(new LookUpColumnInfo("CompanyName"));
}
And this is what my datasource looks like:
I've changed Ian O'Brien's code a little bit and it works:
private void lookUpCompanyPerson_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
{
RepositoryItemLookUpEdit props;
if (sender is LookUpEdit)
props = (sender as LookUpEdit).Properties;
else
props = sender as RepositoryItemLookUpEdit;
if (props != null && (e.Value is int))
{
DataRowView row = props.GetDataSourceRowByKeyValue(e.Value) as DataRowView;
if (row != null)
{
e.DisplayText = String.Format("{0} {1}", row["FirstName"], row["LastName"]);
}
}
}
From the DevExpress documentation:
e.Value gets or sets editor's current value.
e.DisplayText gets or sets an editor's display text
The lookup editor's value is obtained from the data source field specified by the RepositoryItemLookUpEditBase.ValueMember property. The GetDataSourceRowByKeyValue method searches for the specified value within this field and returns an object representing the first found record.
The GetDataSourceRowByKeyValue method's return value depends upon the type of the underlying data source. If the data source is a System.Data.DataTable or a System.Data.DataView, this method returns a System.Data.DataRowView object. If the data source is a custom list of items, the appropriate list item is returned.
You want to set the e.Value to the value that you want to display in the control.
private void lookUpCompanyPerson_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
{
RepositoryItemLookUpEdit props
if (sender is LookUpEdit)
props = (sender as LookUpEdit).Properties;
else
props = sender as RepositoryItemLookUpEdit;
if (props != null && (e.Value is int))
{
object row = props.GetDataSourceRowByKeyValue(e.Value);
if (row != null)
{
e.Value = String.Format("{0} {1}", (DataRowView)row["FirstName"], (DataRowView)row["LastName"]);
e.Handled = true;
}
}
}
Finally, here are some useful pages with more documentation:
BaseEdit.CustomDisplayText Event
RepositoryItemLookUpEdit.GetDataSourceRowByKeyValue Method
i have use it, just like this;
cmb_tip.Properties.DataSource = _dt;
cmb_tip.Properties.ValueMember = "Value";
cmb_tip.Properties.DisplayMember = "Type";
cmb_tip.Properties.PopulateColumns();
cmb_tip.Properties.Columns["Value"].Visible = false;
This is how it works with LookupEditControl in Version 15.2.7 and a Class:
private void lookUpEditPatients_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
{
var edit = sender as LookUpEdit;
var props = edit.Properties;
var pat = (Patients4ComboBoxVm) props?.GetDataSourceRowByKeyValue(e.Value);
if (pat != null)
{
e.DisplayText = pat.Nachname + ", " + pat.Vorname + "; " + pat.Geburtsdatum + "; " + pat.Versicherungsnummer;
}
}

Categories