count the item in PagedDataSource? - c#

I am trying to make paging item counter something like __ of _ items like 1-6 pf 21 item and 6-12 of 21. can someone show me how to do it ??
private void BindResourcesRepater()
{
string tag = Request.QueryString["tag"];
if (String.IsNullOrEmpty(tag))
{
//Guid userID = Guid.Parse(Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString());
DataSet ds = new DataSet();
int selectedTopicID = Convert.ToInt32(ddlTopics.SelectedValue);
int selectedSkillID = Convert.ToInt32(ddlSkills.SelectedValue);
int selectedTypeID = Convert.ToInt32(ddlTypes.SelectedValue);
string keyword = txtbKeyword.Text.Trim();
int sortBy = Convert.ToInt32(ddlSortBy.SelectedValue);
ds = Resource.Search_Resource(selectedTopicID, selectedSkillID, selectedTypeID, keyword, sortBy);
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = ds.Tables[0].DefaultView;
objPds.AllowPaging = true;
objPds.PageSize = 6;
int curpage;
if (ViewState["Page"] != null)
{
curpage = Convert.ToInt32(ViewState["Page"]);
}
else
{
ViewState["Page"] = 1;
curpage = 1;
}
// Set the currentindex
objPds.CurrentPageIndex = curpage - 1;
// Display the current page
// lblCurrentPage.Text = "Page: " + (curpage).ToString() + " of " + objPds.PageCount.ToString();
rp_resList.DataSource = objPds;
rp_resList.DataBind();
if (rp_resList.Items.Count == 0)
{
lnkNext.Visible = false;
if (Convert.ToInt32(ViewState["Page"]) == 1)
{
lnkPrev.Visible = false;
}
else
{
lnkNext.Visible = false;
}
}
else
{
lnkNext.Visible = true;
if (rp_resList.Items.Count < objPds.PageSize)
{
lnkNext.Visible = false;
}
if (Convert.ToInt32(ViewState["Page"]) == 1)
{
lnkPrev.Visible = false;
}
else
{
lnkPrev.Visible = true;
}
}
}
else
{
DataSet ds = new DataSet();
int selectedTopicID = Convert.ToInt32(ddlTopics.SelectedValue);
int selectedSkillID = Convert.ToInt32(ddlSkills.SelectedValue);
int selectedTypeID = Convert.ToInt32(ddlTypes.SelectedValue);
txtbKeyword.Text = tag;
string keyword = tag.ToString();
int sortBy = Convert.ToInt32(ddlSortBy.SelectedValue);
ds = Resource.Search_Resource(selectedTopicID, selectedSkillID, selectedTypeID, tag, sortBy);
lbl_totalResult.Text = ds.Tables[0].Rows.Count.ToString() + " " + "Resources Found";
rp_resList.DataSource = ds.Tables[0];
rp_resList.DataBind();
}
}

Try this:
private void BindResourcesRepater()
{
// your existing code...
int numberOfItems = ds.Tables[0].Rows.Count;
lblCurrentVisibleItems.Text = GetCurrentVisibleItemsText(numberOfItems, objPds.PageSize, objPds.CurrentPageIndex);
}
private string GetCurrentVisibleItemsText(int numberOfItems, int pageSize, int currentPageIndex)
{
int startVisibleItems = currentPageIndex * pageSize + 1;
int endVisibleItems = Math.Min((currentPageIndex + 1) * pageSize, numberOfItems);
return string.Format("Displaying {0}-{1} of {2} items", startVisibleItems, endVisibleItems, numberOfItems);
}
I'm not sure what label you want to display this in, but in my example I've used one called lblCurrentVisibleItems. Replace this with whatever label you want to use.

Related

Text box Auto Generate code not working

I am developing the my asp.net project, I'm try to make ASP.net text box for Auto Generate code, but its not working correctly, sample Auto Generate code = ID1.
I'm try to use this part,
string txt = txtBatchNo.Text;
txtBatchNo.Text = "C" + Convert.ToInt32(txt.Substring(1, txt.Length - 1)) + 1;
Code:
protected void btnAdd_Click(object sender, EventArgs e)
{
int newId = 1;
if (selectGRNDetailId == -1)
{
{
try
{
if (dtFabricItem.Rows.Count > 0)
{
newId = Convert.ToInt32(dtFabricItem.Rows[dtFabricItem.Rows.Count - 1]["GRNDetailsID"].ToString()) + 1;
}
}
catch (Exception)
{
newId = 1;
}
}
}
else
{
newId = selectGRNDetailId;
}
if (dtFabricItem == null)
{
CreateFabricDetails();
dtFabricItem = dt;
}
else
{
CreateFabricDetails();
}
DataRow dr2 = null;
dr2 = dt.NewRow();
dr2["GRNDetailsID"] = newId;
dr2["GRNDetailID"] = selectGRNId;
dr2["BatchNO"] = txtBatchNo.Text;
dr2["ItemId"] = Convert.ToInt32(ddlYarnName.SelectedValue);
dr2["ItemName"] = ddlYarnName.SelectedItem.Text;
dr2["LotId"] = Convert.ToInt32(ddlLotNo.SelectedValue);
dr2["LotName"] = ddlLotNo.SelectedItem.Text;
dr2["FibetLot"] = txtFiberLot.Text;
dr2["ContainsNo"] = txtContainsNO.Text;
dr2["Shade"] = txtShade.Text;
dr2["Quantity"] = Convert.ToDecimal(txtQty.Text).ToString();
dr2["YarnPrice"] = Convert.ToDecimal(txtYarnPrice.Text).ToString();
dr2["Cornweight"] = Convert.ToDecimal(txtCornWeight.Text).ToString();
dr2["BoxWeight"] = Convert.ToDecimal(txtBoxWeight.Text).ToString();
dr2["NumberofCones"] = Convert.ToDecimal(txtNumberofcones.Text).ToString();
dr2["Numberofboxes"] = Convert.ToDecimal(txtNumberofboxes.Text).ToString();
dt.Rows.Add(dr2);
//txtNumberofcones.Text = (Convert.ToDecimal(txtBoxWeight.Text) / Convert.ToDecimal(txtCornWeight.Text)).ToString();
if (dtFabricItem == null || dtFabricItem.Rows.Count == 0)
{
dtFabricItem = dt;
dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
}
else
{
dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
dtFabricItem.Merge(dt);
}
//dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
dtFabricItem.AcceptChanges();
gvrItemDetails.DataSource = dtFabricItem;
gvrItemDetails.DataBind();
selectGRNDetailId = -1;
ClearDetails();
}
TextBox Id = `txtBatchNo`

Insert multiple records in database using parallel.foreach

I am trying to insert around 5000 records in database using foreach loop. It is taking around 10 min which is not acceptable as per the requirement. I also thought about the approach in which first insert the records in a datatable and then converting it into XML pass it to stored procedure which do the insertion. But unfortunately it is not getting fit in my situation. Now i am doing the same thing using parallel.foreach but after inserting 10 records i am getting "Unique constraint violation for the primary key" error msg. As i am new to parallel programming so not getting the solution for it. Below is my code that i have done so for.
public ActionResult ChannelBulkUpload(HttpPostedFileBase excelFile)
{
bool flag = true;
string path = Server.MapPath("~/Content/UploadFolder/" + excelFile.FileName);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
excelFile.SaveAs(path);
DataTable dt = GetDataTableFromExcel(excelFile, true);
ParallelOptions options = new ParallelOptions
{
MaxDegreeOfParallelism = 4
};
Parallel.ForEach(dt.AsEnumerable(), row =>
{
flag = true;
decimal Key = 0;
string value = "";
decimal channelMstKey = 0;
decimal channelGrpMstKey = 0;
decimal srcFuncKey = 0;
string ExcelMasterChDisplayName = row["MASTER_CHANNEL_DISPLAY_NAME"].ToString();
string ExcelGenreValue = row["GENRE"].ToString();
string ExcelAdsharpValue = row["ADSHARP"].ToString();
string ExcelClusterValue = row["CLUSTER"].ToString();
string ExcelNetworkValue = row["NETWORK"].ToString();
string ExcelBroadCastValue = row["BROADCAST"].ToString();
string ExcelFunctionalAreaname = row["FUNCTIONAL_AREA"].ToString();
string[] Ch_Grp_types = { "GENRE", "ADSHARP", "CLUSTER", "NETWORK", "PLATFORM" };
BarcDataContext bc = new BarcDataContext();
srcFuncKey = bc.REF_SRC_FUNC_AREA.Where(m => m.SRC_FUNC_AREA == ExcelFunctionalAreaname).FirstOrDefault().SRC_FUNC_KEY;
for (int j = 0; j < Ch_Grp_types.Length && flag; j++)
{
if (Ch_Grp_types[j] == "GENRE")
{
Key = 1;
value = ExcelGenreValue;
}
else if (Ch_Grp_types[j] == "NETWORK")
{
Key = 2;
value = ExcelNetworkValue;
}
else if (Ch_Grp_types[j] == "ADSHARP")
{
Key = 3;
value = ExcelAdsharpValue;
}
else if (Ch_Grp_types[j] == "CLUSTER")
{
Key = 4;
value = ExcelClusterValue;
}
else if (Ch_Grp_types[j] == "PLATFORM")
{
Key = 5;
value = ExcelBroadCastValue;
}
DIM_CHANNEL_MST objChMst = bc.DIM_CHANNEL_MST.Where(m => m.CHANNEL_MST_NAME_UPPER == ExcelMasterChDisplayName.ToUpper().Trim()).FirstOrDefault();
if (objChMst == null)
{
flag = false;
}
else
{
if (!string.IsNullOrEmpty(value))
{
var query =
(from A in bc.XREF_CH_GRP_DET_TAG
join B in bc.XREF_CH_GRP_MST_TAG on A.CH_GRP_MST_KEY equals B.CH_GRP_MST_KEY
where A.IS_ACTIVE == "Y" && B.IS_ACTIVE == "Y" && B.CH_GRP_TYPE_KEY == Key && B.CH_GRP_MST_NAME_UPPER == value.ToUpper()
select new XrefChannelGrpDetailTagVM
{
channelGrpDetKey = A.CH_GRP_DET_KEY,
channelGrpMasterNameUpper = B.CH_GRP_MST_NAME_UPPER,
}).Distinct().ToList();
var query2 =
(from A in bc.XREF_CH_GRP_DET_TAG
join B in bc.XREF_CH_GRP_MST_TAG on A.CH_GRP_MST_KEY equals B.CH_GRP_MST_KEY
where A.CHANNEL_MST_KEY == objChMst.CHANNEL_MST_KEY && B.CH_GRP_TYPE_KEY == Key && B.SRC_FUNC_KEY == srcFuncKey
select new XrefChannelGrpDetailTagVM
{
sr_no = A.SR_NO,
channelMstKey = A.CHANNEL_MST_KEY,
channelGrpDetKey = A.CH_GRP_DET_KEY,
channelGrpMstKey = A.CH_GRP_MST_KEY,
srcFuncKey = B.SRC_FUNC_KEY,
channelGrpTypeKey = B.CH_GRP_TYPE_KEY
}).Distinct().ToList();
XREF_CH_GRP_MST_TAG objXrefChGrpMst = bc.XREF_CH_GRP_MST_TAG.Where(m => m.CH_GRP_TYPE_KEY == Key && m.SRC_FUNC_KEY == srcFuncKey && m.CH_GRP_MST_NAME_UPPER == value.ToUpper()).FirstOrDefault();
if (objXrefChGrpMst != null)
{
channelMstKey = objChMst.CHANNEL_MST_KEY;
channelGrpMstKey = objXrefChGrpMst.CH_GRP_MST_KEY;
XREF_CH_GRP_DET_TAG objGrpDetail = new XREF_CH_GRP_DET_TAG();
if (query.Count == 0)
{
objGrpDetail.CH_GRP_DET_KEY = Get_Max_Of_Ch_Grp_Det_Key();
}
else
{
foreach (var detKey in query)
{
if (detKey.channelGrpMasterNameUpper == value.ToUpper())
{
objGrpDetail.CH_GRP_DET_KEY = detKey.channelGrpDetKey;
}
else
{
objGrpDetail.CH_GRP_DET_KEY = Get_Max_Of_Ch_Grp_Det_Key();
}
}
}
if (query2.Count > 0)
{
foreach (var abc in query2)
{
if (abc.channelMstKey == objChMst.CHANNEL_MST_KEY && abc.srcFuncKey == srcFuncKey && abc.channelGrpTypeKey == Key)
{
if (abc.channelGrpDetKey == objGrpDetail.CH_GRP_DET_KEY && abc.channelGrpMstKey == objXrefChGrpMst.CH_GRP_MST_KEY)
{
//Reject
}
else
{
//Update
XREF_CH_GRP_DET_TAG obj = bc.XREF_CH_GRP_DET_TAG.Where(m => m.SR_NO == abc.sr_no).FirstOrDefault();
obj.CH_GRP_DET_KEY = objGrpDetail.CH_GRP_DET_KEY;
obj.CH_GRP_MST_KEY = objXrefChGrpMst.CH_GRP_MST_KEY;
objGrpDetail.CREATE_DATE = DateTime.Now;
objGrpDetail.LAST_UPD_DATE = DateTime.Now;
objGrpDetail.IS_ACTIVE = "Y";
bc.SaveChanges();
}
}
else
{
//Insert
objGrpDetail.CH_GRP_MST_KEY = channelGrpMstKey;
objGrpDetail.CHANNEL_MST_KEY = channelMstKey;
objGrpDetail.SR_NO = Get_Max_Of_XREF_CH_GRP_DET();
objGrpDetail.CREATE_DATE = DateTime.Now;
objGrpDetail.LAST_UPD_DATE = DateTime.Now;
objGrpDetail.IS_ACTIVE = "Y";
bc.XREF_CH_GRP_DET_TAG.Add(objGrpDetail);
bc.SaveChanges();
}
}
}
else
{
objGrpDetail.CH_GRP_MST_KEY = channelGrpMstKey;
objGrpDetail.CHANNEL_MST_KEY = channelMstKey;
objGrpDetail.SR_NO = Get_Max_Of_XREF_CH_GRP_DET();
objGrpDetail.CH_GRP_DET_KEY = objGrpDetail.CH_GRP_DET_KEY;
objGrpDetail.CREATE_DATE = DateTime.Now;
objGrpDetail.LAST_UPD_DATE = DateTime.Now;
objGrpDetail.IS_ACTIVE = "Y";
bc.XREF_CH_GRP_DET_TAG.Add(objGrpDetail);
bc.SaveChanges();
}
}
}
}
}
});
TempData["SuccessMsg"] = "Records uploaded Successfully";
return RedirectToAction("CreateChannel");
}
Getting error when generating the primary key value using the below function :
public static decimal Get_Max_Of_XREF_CH_GRP_DET()
{
try
{
BarcDataContext bc = new BarcDataContext();
return bc.XREF_CH_GRP_DET_TAG.Max(m => m.SR_NO) + 1;
}
catch (Exception e)
{
return 1;
}
}
Where SR_NO is the primary key in that table.
Any help will be very much appreciated. Thanks in advance.
The fastest way to do such inserts is using ADO.NET, specifically, SQL Bulk Insert. If you're using SQL Server as your database, the relevant code will be something like this:
DataTable dt = GetDataTableFromExcel(excelFile, true);
using (var copy = new SqlBulkCopy(yourConnectionString) //There are other overloads too
{
BulkCopyTimeout = 10000,
DestinationTableName = dt.TableName,
})
{
foreach (DataColumn column in dt.Columns)
{
copy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
}
copy.WriteToServer(dt);
}
Please look at my comment to other question
You could use guid as primary key into your table. It would help you to avoid problem with ##IDENTITY. At first you should generate new guid-identity, thank insert the generated value into a row

ASP.net Adding Multiple Table Entries to Database

I am using Visual Studio 2015 and Entity Framework 6. I am trying to add entries from inputted information into multiple tables.
This is what I have so far:
protected void btnOrder_Click(object sender, EventArgs e)
{
using (FlowerCompanyEntities flower = new FlowerCompanyEntities())
{
int rFlowers = 0;
Boolean rVase = false;
DateTime DeliveryDate = DateTime.Parse(tbDelivery.Text);
string flowerArrangement = ddlListFlowers.SelectedValue;
if (flowerArrangement == "f2")
{
rFlowers = 1;
}
if (flowerArrangement == "f3")
{
rFlowers = 2;
}
if (flowerArrangement == "f1")
{
rFlowers = 3;
}
if (flowerArrangement == "f4")
{
rFlowers = 4;
}
if (flowerArrangement == "f5")
{
rFlowers = 5;
}
string vase = rbList.SelectedItem.Value.ToString();
if (vase == "NO")
{
rVase = false;
}
if (vase == "YES")
{
rVase = true;
}
Customers cust = new Customers();
Addresses Addr = new Addresses();
Phone Pho = new Phone();
Delivery Del = new Delivery();
Arrangements arr = new Arrangements();
OrderStatus ordstat = new OrderStatus();
Orders ord = new Orders();
Pho.Phone1 = tbPhone.Text;
Addr.Street = tbStreet.Text;
Addr.City = tbCity.Text;
Addr.States = tbState.Text;
Addr.Zip = tbZip.Text;
cust.FirstName = tbFirstName.Text;
cust.LastName = tbLastName.Text;
Del.DeliverDate = DeliveryDate;
arr.FlowerID = rFlowers;
ordstat.OrderStatus1 = tbStatus.Text;
ord.Vase = rVase;
ord.OrderMessage = tbOrderMessage.Text;
try {
flower.Phone.Add(Pho);
flower.Addresses.Add(Addr);
flower.Customers.Add(cust);
flower.Delivery.Add(Del);
flower.Arrangements.Add(arr);
flower.OrderStatus.Add(ordstat);
flower.Orders.Add(ord);
flower.SaveChanges();
Response.Redirect("Orders.aspx");
}
catch { }
}
However, on the button click i get an exception error. I also just realized that some of those tables -- with those entries would need the foreign key of the other tables put in.
Question: How do I add all these entries to my database when there is multiple tables and foreign keys?

Unable to modify a dataset before binding to gridview in asp.net

I need to modify a dataset before binding it to a gridview.
When I walk through the complete code block, and hover over dsEmployeeOrg, that records
dont appear modified. What am I missing here?
My code is:
DataSet dsEmployeeOrg = eCorporateStaffMgr.GetEmployeeAccessLevel(oEmp);
DataTable dt = dsEmployeeOrg[0];
string sManagerID = "";
string sSupervisorID = "";
string sEmployeeID = "";
for (int i = 0; i < dsEmployeeOrg.Tables[0].Rows.Count; i++)
{
sManagerID = dt.Rows[i].ItemArray[3].ToString().Trim();
sSupervisorID = dt.Rows[i].ItemArray[4].ToString().Trim();
sEmployeeID = dt.Rows[i].ItemArray[5].ToString().Trim();
if ((sManagerID.ToString().Trim() != sSupervisorID.ToString().Trim()) && (sManagerID.ToString().Trim() != sEmployeeID.ToString().Trim()))
{
if (sSupervisorID.ToString().Trim() == sEmployeeID.ToString().Trim())
{
// This is a Supervisor record
dt.Rows[i].ItemArray[2] = "1111";
}
else if (sSupervisorID.ToString().Trim() != sEmployeeID.ToString().Trim())
{
//This is a Employee record
dt.Rows[i].ItemArray[2] = "0000";
}
}
}
Please modify your code as below
DataSet dsEmployeeOrg = eCorporateStaffMgr.GetEmployeeAccessLevel(oEmp);
DataTable dt = dsEmployeeOrg[0];
string sManagerID = "";
string sSupervisorID = "";
string sEmployeeID = "";
for (int i = 0; i < dsEmployeeOrg.Tables[0].Rows.Count; i++)
{
sManagerID = dt.Rows[i].ItemArray[3].ToString().Trim();
sSupervisorID = dt.Rows[i].ItemArray[4].ToString().Trim();
sEmployeeID = dt.Rows[i].ItemArray[5].ToString().Trim();
if ((sManagerID.ToString().Trim() != sSupervisorID.ToString().Trim()) && (sManagerID.ToString().Trim() != sEmployeeID.ToString().Trim()))
{
if (sSupervisorID.ToString().Trim() == sEmployeeID.ToString().Trim())
{
// This is a Supervisor record
dt.Rows[i][2] = "1111";
}
else if (sSupervisorID.ToString().Trim() != sEmployeeID.ToString().Trim())
{
//This is a Employee record
dt.Rows[i][2] = "0000";
}
}
}

How To update Text box contents after a selection change in ListPicker in windows phone 7?

I have to update my txtid , txtName ,txtAge ,txtContact..OnSelectionChange of ListPicker , but even after selecting items it is not updating txtfields . How can i step up on it ?
public partial class Update : PhoneApplicationPage
{
Button btnUpdate1 = null;
TextBox txtid = null;
TextBox txtName = null;
TextBox txtAge = null;
TextBox txtContact = null;
ListPicker lp = null;
int selectedItem ;
public Update()
{
InitializeComponent();
int x = noofrows();
createUpdateButton();
createListPicker();
selectedItem = Convert.ToInt32(lp.SelectedItem);
createTxtId(selectedItem);
createTxtName(selectedItem);
createTxtAge(selectedItem);
createTxtContact(selectedItem);
}
public void createListPicker()
{
lp = new ListPicker();
lp.BorderBrush = new SolidColorBrush(Colors.White);
lp.BorderThickness = new Thickness(3);
lp.Margin = new Thickness(12, 5, 0, 0);
lp.Width = 400;
int x = noofrows();
for (int a = 1; a <= x; a++)
{
string str1 = returnID(a);
lp.Items.Add(str1);
}
lp.SelectionChanged += (s, e) =>
{
selectedItem = Convert.ToInt32(lp.SelectedItem);
};
LayoutRoot.Children.Add(lp);
}
public void createUpdateButton()
{
btnUpdate1 = new Button();
btnUpdate1.Margin = new Thickness(100, 600, 0, 0);
btnUpdate1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
btnUpdate1.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
btnUpdate1.Height = 100;
btnUpdate1.Width = 150;
btnUpdate1.Content = "update";
btnUpdate1.Foreground = new SolidColorBrush(Colors.White);
btnUpdate1.Background = new SolidColorBrush(Colors.Black);
btnUpdate1.BorderBrush = new SolidColorBrush(Colors.White);
btnUpdate1.BorderThickness = new Thickness(3);
btnUpdate1.FontSize = 28;
LayoutRoot.Children.Add(btnUpdate1);
btnUpdate1.Click += (s, e) =>
{
UpdateDatabase(selectedItem);
};
}
public void createTxtId(int z)
{
int id = z ;
txtid = new TextBox();
txtid.Margin = new Thickness(12, 100, 0, 0);
txtid.Width = 400;
txtid.Height = 100;
txtid.FontSize = 28;
txtid.Foreground = new SolidColorBrush(Colors.Black);
txtid.BorderBrush = new SolidColorBrush(Colors.Black);
txtid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtid.BorderThickness = new Thickness(3);
txtid.IsReadOnly = true;
txtid.Text = " " + id;
LayoutRoot.Children.Add(txtid);
}
public void createTxtName(int z)
{
txtName = new TextBox();
txtName.Margin = new Thickness(12, 200, 0, 0);
txtName.Width = 400;
txtName.Height = 100;
txtName.FontSize = 28;
txtName.Foreground = new SolidColorBrush(Colors.Black);
txtName.BorderBrush = new SolidColorBrush(Colors.Black);
txtName.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtName.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtName.BorderThickness = new Thickness(3);
txtName.Text = SelectName(z);
txtName.Tap += (s, e) =>
{
if (txtName.Text == "Name")
{
txtName.Text = "";
}
};
txtName.LostFocus += (s, e) =>
{
if (txtName.Text == "")
{
txtName.Text = "Name";
}
};
LayoutRoot.Children.Add(txtName);
}
public void createTxtAge(int z)
{
txtAge = new TextBox();
txtAge.Margin = new Thickness(12, 300, 0, 0);
txtAge.Width = 400;
txtAge.Height = 100;
txtAge.FontSize = 28;
txtAge.Foreground = new SolidColorBrush(Colors.Black);
txtAge.BorderBrush = new SolidColorBrush(Colors.Black);
txtAge.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtAge.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtAge.BorderThickness = new Thickness(3);
txtAge.MaxLength = 2;
txtAge.Text = SelectAge(z);
txtAge.InputScope = new InputScope();
txtAge.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.Number });
txtAge.Tap += (s, e) =>
{
if (txtAge.Text == "Age")
{
txtAge.Text = "";
}
};
txtAge.LostFocus += (s, e) =>
{
if (txtAge.Text == "")
{
txtAge.Text = "Age";
}
};
LayoutRoot.Children.Add(txtAge);
}
public void createTxtContact(int z)
{
txtContact = new TextBox();
txtContact.Margin = new Thickness(12, 400, 0, 0);
txtContact.Width = 400;
txtContact.Height = 100;
txtContact.FontSize = 28;
txtContact.MaxLength = 10;
txtContact.Foreground = new SolidColorBrush(Colors.Black);
txtContact.BorderBrush = new SolidColorBrush(Colors.Black);
txtContact.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtContact.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtContact.BorderThickness = new Thickness(3);
txtContact.Text = SelectContact(z);
txtContact.InputScope = new InputScope();
txtContact.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.Number });
txtContact.Tap += (s, e) =>
{
if (txtContact.Text == "Contact")
{
txtContact.Text = "";
}
};
txtContact.LostFocus += (s, e) =>
{
if (txtContact.Text == "")
{
txtContact.Text = "Contact";
}
};
LayoutRoot.Children.Add(txtContact);
}
public Int32 noofrows()
{
int b = Convert.ToInt32((Application.Current as App).db.SelectList("select count(*) from details"));
return b;
}
public string returnID(int z)
{
return Convert.ToString((Application.Current as App).db.SelectList("select id from details where id =" + z));
}
public String SelectName(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select name from details where id =" + x));
}
public String SelectAge(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select age from details where id =" + x));
}
public String SelectContact(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select contact from details where id =" + x));
}
public void UpdateDatabase(int ID)
{
if (txtName.Text=="Name")
{
MessageBox.Show("Enter a valid Name");
}
else if (txtAge.Text.Length>=3||txtAge.Text=="Age")
{
MessageBox.Show("Enter A valid Age (1-99)");
}
else if (txtContact.Text.Length != 10)
{
MessageBox.Show("Enter a valid Mobile number Of 10 digit");
}
else
{
string s1 = "update details set id='" + Convert.ToInt64(txtid.Text) + "', name = '" + txtName.Text + "', age = '" + txtAge.Text + "', contact = '" + txtContact.Text + "'where id = " + ID;
string s2 = Convert.ToString((Application.Current as App).db.SelectList(s1));
MessageBox.Show("Updated Successfully");
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
}
You are using so much code. Its would be better if you follow the MVM architecture and try to set Bind the textblocks to your viewModel. Lets consider the following scenario.
You have binded the xaml elements to selectedItem in your viewModel. Now when selectedItem's value is changed Notify event is triggered which will notify the UI and the values will automatically be updated.
I recommend you to study viewmodel and try to implement it. Its really easy and would save you a lot of hassle.
Try implementing some samples
Hope it helps :)
I got this ...
Actually if we want to update that we need to change text of each text box . So after the selection change , Try it like this.
public void createListPicker()
{
lp = new ListPicker();
lp.BorderBrush = new SolidColorBrush(Colors.White);
lp.BorderThickness = new Thickness(3);
lp.Margin = new Thickness(12, 5, 0, 0);
lp.Width = 400;
int x = noofrows();
for (int a = 1; a <= x; a++)
{
string str1 = returnID(a);
lp.Items.Add(str1);
}
lp.SelectionChanged += (s, e) =>
{
selectedItem = Convert.ToInt32(lp.SelectedItem);
txtid.Text = selectedItem.ToString();
txtName.Text = SelectName(selectedItem);
txtAge.Text = SelectAge(selectedItem);
txtContact.Text = SelectContact(selectedItem);
};
LayoutRoot.Children.Add(lp);
}
This will update Immediately after Every selection change Event .

Categories

Resources