How to handle 'The source contains no DataRows. ' error - asp.net

please find below code.It will through an error 'The source contains no DataRow' if ithe row is empty..How to handle this ??
if (dtTemSec.Rows.Count > 0)
{
grdStepDetails.DataSource = dtTemSec.AsEnumerable()
.Where(x => x.Field<string>("Status") != "D" && x.Field<string>("ID") == "ST" && x.Field<int>("Folder") == folder)
.CopyToDataTable();
grdStepDetails.DataBind();
ClientScript.RegisterStartupScript(GetType(), "Val", "ShowStepPopup();", true);
}
else
{
grdStepDetails.DataSource = null;
grdStepDetails.DataBind();
ClientScript.RegisterStartupScript(GetType(), "Val", "ShowStepPopup();", true);
}

Use like this :-
if (dtTemSec.Rows.Count > 0)
{
var table = dtTemSec;
var rows = table.AsEnumerable().Where(x => x.Field<string>("Status") != "D" && x.Field<string>("ID") == "ST" && x.Field<int>("Folder") == folder);
var dt = rows.Any() ? rows.CopyToDataTable() : table.Clone();
grdStepDetails.DataSource = dt;
grdStepDetails.DataBind();
ClientScript.RegisterStartupScript(GetType(), "Val", "ShowStepPopup();", true);
}
else
{
grdStepDetails.DataSource = null;
grdStepDetails.DataBind();
ClientScript.RegisterStartupScript(GetType(), "Val", "ShowStepPopup();", true);
}

Use a If condition as below.
if(dtTemSec != null)
{
if(dtTemSec.Rows.Count > 0)
{
}
}
EDIT:
If that is the case, then put the condition after the Filter
if(dtTemSec != null)
{
if(dtTemSec.Rows.Count > 0)
{
DataTable Temp = new DataTable();
Temp = dtTemSec.AsEnumerable()
.Where(x => x.Field<string>("Status") != "D" && x.Field<string>("ID") == "ST" && x.Field<int>("Folder") == folder)
.CopyToDataTable();
if(Temp != null)
{
if(Temp.Rows.Count > 0)
{
grdStepDetails.DataSource=Temp;
grdStepDetails.DataBind();
ClientScript.RegisterStartupScript(GetType(), "Val", "ShowStepPopup();", true);
}
}
}
}

Related

How to populate data related to an item from the location which is same for all items in Xamarin.forms

I am developing an xamarin.forms app ,I have various fields like Item Name ,Item Number and location ,here Location of all the items are same ,by entering names or number of the items the values are generated automatically because name and number are unique but since the location number is common is for all the items I am not able to populate correct data related to a particular field ,I am using sqlite database in my project can anyone please suggest me on what basis can I generate related values ?
Here is the code
public async void OnSearch_Location(object o, EventArgs args)
{
if (location.Text == string.Empty || location.Text == null)
{
await Navigation.PushAsync(new ListValuePage("Location", filePath,
pos, list));
}
else
{
for (int p = 0; p < list.Count; p++)
{
if (list.ElementAt(p).Aisle + "." + list.ElementAt(p).Bin +
"." + list.ElementAt(p).Level == location.Text)
{
line.Text =
Convert.ToString(list.ElementAt(p).Line_Number);
location.Text = list.ElementAt(p).Aisle + "." +
list.ElementAt(p).Bin + "." + list.ElementAt(p).Level;
item.Text = list.ElementAt(p).Item_Number;
name.Text = list.ElementAt(p).Name;
if (list.ElementAt(p).Order_Qty == 0)
{
order_uom.Text = "";
}
else
{
order_qty.Text =
Convert.ToString(list.ElementAt(p).Order_Qty);
}
order_uom.Text = list.ElementAt(p).Order_UOM;
if (list.ElementAt(p).Consumption_UOM == string.Empty ||
list.ElementAt(p).Consumption_UOM == null)
{
consume_lbl.IsVisible = false;
consume_qty.IsVisible = false;
consume_uom.IsVisible = false;
}
else
{
consume_lbl.IsVisible = true;
consume_qty.IsVisible = true;
consume_uom.IsVisible = true;
if (list.ElementAt(p).Consumption_Qty == 0)
{
consume_qty.Text = "";
}
else
{
consume_qty.Text =
Convert.ToString(list.ElementAt(p).Consumption_Qty);
}
consume_uom.Text = list.ElementAt(p).Consumption_UOM;
}
}
}
}
}

web api call performance tuning

I am trying to figure find why my api is taking ~5 secs working on 1000 records,is that good or bad?I want to know what tools are there in asp.net webapi to figure out which piece of code or where its consuming time and fine tune the performance
CODE:-
List<LookaheadRunInfo> lookaheadRunsInfo = new List<LookaheadRunInfo>();
List<lookahead_run> lookaheadRunData = new List<lookahead_run>();
if (!filterCriteria.labeled)
{
lookaheadRunData = bitDB.lookahead_run.Where(x => x.lookahead_run_status == null && x.submission_time != null).OrderByDescending(x => x.submission_time).Skip(filterCriteria.PageNumber * filterCriteria.PageSize).Take(filterCriteria.PageSize).ToList();
}
else
{
lookaheadRunData = bitDB.lookahead_run.OrderByDescending(x => x.submission_time).Skip(filterCriteria.PageNumber * filterCriteria.PageSize).Take(filterCriteria.PageSize).ToList();
}
foreach (var lookaheadRunRow in lookaheadRunData)
{
var lookaheadRunInfo = new LookaheadRunInfo();
var lookaheadRunId = lookaheadRunRow.lookahead_run_id;
lookaheadRunInfo.ECJobLink = lookaheadRunRow.ec_job_link;
lookaheadRunInfo.UserSubmitted = lookaheadRunRow.submitted_by;
lookaheadRunInfo.SubmittedTime = lookaheadRunRow.submission_time.ToString();
lookaheadRunInfo.RunStatus = lookaheadRunRow.lookahead_run_status;
var completionTime = lookaheadRunRow.completion_time;
if (completionTime == null)
{
lookaheadRunInfo.ElapsedTime = (DateTime.UtcNow - lookaheadRunRow.submission_time).ToString();
}
else
{
lookaheadRunInfo.ElapsedTime = (lookaheadRunRow.completion_time - lookaheadRunRow.submission_time).ToString();
}
List<String> gerrits = new List<String>();
List<string> lookaheadRunChangeListIds = new List<string>();
if (!filterCriteria.labeled)
{
lookaheadRunChangeListIds = (from lrcl in bitDB.lookahead_run_change_list
join cl in bitDB.change_lists on lrcl.change_list_id equals cl.change_list_id
where lrcl.lookahead_run_id == lookaheadRunId
//and cl.change_list_id not in (select clcl.change_list_id from component_labels_change_lists as clcl)
//where !(from clcl in bitDB.component_labels_change_lists select clcl.change_list_id).Contains(cl.change_list_id)
where !bitDB.component_labels_change_lists.Any(clcl => clcl.change_list_id == cl.change_list_id)
select cl.change_list.ToString()).ToList();
}
else
{
lookaheadRunChangeListIds = (from lrcl in bitDB.lookahead_run_change_list
join cl in bitDB.change_lists on lrcl.change_list_id equals cl.change_list_id
where lrcl.lookahead_run_id == lookaheadRunId
select cl.change_list.ToString()).ToList();
}
//bitDB.Log = Console.Out;
//lookaheadRunInfo.gerrits = gerrits;
lookaheadRunInfo.gerrits = lookaheadRunChangeListIds;
if (lookaheadRunChangeListIds.Count != 0 && filterCriteria.labeled == false)
{
lookaheadRunsInfo.Add(lookaheadRunInfo);
}
else if (filterCriteria.labeled == true)
{
lookaheadRunsInfo.Add(lookaheadRunInfo);
}
}
return lookaheadRunsInfo;

Cant filter dynamic query

Hi i got question for the entity query. Please see my code
var list = from table in db.USER_BETTINGS
where table.UserID == UserId
&& table.UserID !="admin"
//&& table.WinningAfterRebate != 0m
&& table.BettingTransactionTime >= fromDate &&
table.BettingTransactionTime <= toDAte
//&& table.WinningAfterRebate !=0m
// orderby table.BettingTransactionNumber descending//table.BettingNumber descending//, table.BettingTransactionTime descending//
select table;
if (loteryNumber != 0)
{
list= list.Where(x => x.LotteryNumber == loteryNumber);
}
if (gameNum != 0)
{
list= list.Where(x => x.GameNumber == gameNum);
}
if (periodDate != "")
{
list= list.Where(x => x.PeriodDate == periodDate);
}
if (close.Equals("Y"))
{
list= list.Where(w => w.WinningAfterRebate != 0m);
}
else
{
list= list.Where(x => x.WinningAfterRebate == 0);
}
But the list not filtering , It return all record? Anyone got face this problem before?
You need some makeover in this code. You have unnecessarily used so many if condition, we need to get rid of that first. Change your query with the following.
var list =( from table in db.USER_BETTINGS
where table.UserID == UserId
&& table.UserID !="admin"
&& table.BettingTransactionTime >= fromDate
&& table.BettingTransactionTime <= toDAte
&& table.LotteryNumber == (loteryNumber != 0 ? loteryNumber : table.LotteryNumber)
&& table.GameNumber == (gameNum != 0 ? gameNum : table.GameNumber)
&& table.PeriodDate == (periodDate != string.Empty ? periodDate : table.PeriodDate )
&& (close.Equals("Y") ? table.WinningAfterRebate != 0 : table.WinningAfterRebate == 0)
).ToList();

selecting checkbox from checkbox list on condition

i have 5 checkboxlists, and each of the checkboxlists have the same 6 checkboxes.
i have to check these checkboxlists during page_Load under certain conditions.
How do i do that.?
for (int j = 0; j < no_of_listitem; j++)
{
SqlCommand check = new SqlCommand("SELECT ISGoal1, ISGoal2,ISGoal3, ISGoal4,ISGoal5 FROM PRM2011_EMPLOYEE_GOAL WHERE EmployeeID = '" + employeeid[j] + "'", con);
SqlDataReader y = check.ExecuteReader();
while (y.Read())
{
if (null != y && y.HasRows)
{
string yes_or_no = y["ISGoal1"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList1.Items[j].Selected = true;
}
//else CheckBoxList1.Items[j].Selected = false;
yes_or_no = y["ISGoal2"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList2.Items[j].Selected = true;
}
//else CheckBoxList2.Items[j].Selected = false;
yes_or_no = y["ISGoal3"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList3.Items[j].Selected = true;
}
//else CheckBoxList3.Items[j].Selected = false;
yes_or_no = y["ISGoal4"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList4.Items[j].Selected = true;
}
//else CheckBoxList4.Items[j].Selected = false;
yes_or_no = y["ISGoal5"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList5.Items[j].Selected = true;
}
//else CheckBoxList5.Items[j].Selected = false;
}
}
y.Close();
}
employeeid[] contains id of 6 employees.no_of_listitems is 6 which is the list of thses 6 employee ids.
Create a list with your CheckBoxList in it. Then, replace the code with something like this:
for(int z = 1; z <= checkboxLists.Count; z++)
{
checkboxLists[z].Items[j].Selected = y["ISGoal" + z].ToString().Trim() == "yes";
}
Keep in mind though that this code is not type-safe. Normally, you'd want to avoid using string in your code and y["ISGoal"+z] might be null. If it is, the application will crash. This mean you want to make checks to make sure it's ok. Trying to make a ToString() or Trim() on null will make a NullPointerException. You might also want to change "yes" by bit in your database. It would be much more safe to work with. What if someone writes "true" instead of yes?
I hope it helps out. If you have any question, don't hesitate.

Null reference exception

I have a function like this
public bool CheckMentorAccess()
{
bool blnAllow = false;
try
{
string strSelectMentorQuery = "SELECT COUNT(DISTINCT MLL.LED_ID) FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL " + "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString() + "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND" + " MLL.END_DATE > Getdate()";
int intNoOfMembers = Convert.ToInt32(cSQLHelper.myExecuteScalar(strSelectMentorQuery));
if (intNoOfMembers > 0)
{
blnAllow = true;
}
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
blnAllow = false;
}
// Return the value
return blnAllow;
}
And then I use if like this
if ((Int32.Parse(Session["ROLE_ID"].ToString()) == 3) && (CheckMentorAccess() == true))
{
cmbempList.Visible = true;
}
but it is throwing a null reference exception on the first line of the sample above
Can anyone help me out..
You can try
if (Session["ROLE_ID"] != null && (Int32.Parse(Session["ROLE_ID"].ToString()) == 3) && (CheckMentorAccess() == true))
{
cmbempList.Visible = true;
}
First check that Session["ROLE_ID"] exists before you use ToString.
It is always safer to use Convert.ToString.
Well, if the stack trace only points at that line, I'd guess this is the problem:
Int32.Parse(Session["ROLE_ID"].ToString())
That will throw a NullReferenceException if Session["ROLE_ID"] returns null.
(It will throw FormatException if the value exists in the session but isn't a valid integer.)
It's possible that it's the call to CheckMentor() which is failing, of course - but then your stack trace should say so. That could fail if cSQLHelper is null, for example.
Try this - check the values you are using when you call the method:
if (Session["ROLE_ID"] != null)
{
if ((Int32.Parse(Session["ROLE_ID"]) == 3) && (CheckMentorAccess()))
{
cmbempList.Visible = true;
}
}
and check in the method
public bool CheckMentorAccess()
{
if (Session["UserID"] == null)
{
throw new NullReferenceException("UserID is null");
}
bool blnAllow = false;
try
{
string strSelectMentorQuery = "SELECT COUNT(DISTINCT MLL.LED_ID) FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL " + "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString() + "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND" + " MLL.END_DATE > Getdate()";
int intNoOfMembers = Convert.ToInt32(cSQLHelper.myExecuteScalar(strSelectMentorQuery));
blnAllow = intNoOfMembers > 0;
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
blnAllow = false;
}
// Return the value
return blnAllow;
}

Resources