Using xamarin I would like to add a few pins to map to make a route.
My API for adding pins:
{"Id":1,"X":1.0,"Y":2.0,"RouteId":1,"Route":null}
My API for adding routes:
{"Id":1,"Name":"dd","Description":"fff"}
"RouteId:1" is associated with "Id:1"
I would like to create a route by pressing the button(OnNewRouteClicked)
My code:
public partial class CreatorPage : ContentPage
{
private CustomPin pin;
public CreatorPage()
{
InitializeComponent();
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(53.010281, 18.604922), Distance.FromMiles(1.0)));
}
private void OnClearClicked(object sender, EventArgs e)
{
customMap.Pins.Clear();
customMap.MapElements.Clear();
}
private async void OnMapClicked(object sender, MapClickedEventArgs e)
{
if (String.IsNullOrWhiteSpace(nazwaEntry.Text))
{
await DisplayAlert("Błąd", "Podaj nazwę punktu", "Ok");
return;
}
CustomPin pin = new CustomPin
{
Type = PinType.SavedPin,
Position = new Position(e.Position.Latitude, e.Position.Longitude),
Label = nazwaEntry.Text,
Address = opisEntry.Text,
Name = "Xamarin",
Url = "http://xamarin.com/about/",
Question = zagadkaEntry.Text,
Answer = odpowiedzEntry.Text
};
pin.MarkerClicked += async (s, args) =>
{
args.HideInfoWindow = true;
string pinName = ((CustomPin)s).Label;
// string pytanie = ((CustomPin)s).Question;
string opis = ((CustomPin)s).Address;
// string odpowiedz = ((CustomPin)s).Answer;
await DisplayAlert($"{pinName}", $"{opis}", "Quiz");
// await DisplayAlert("Quiz", $"{pytanie}", "Przejdź do odpowiedzi");
await Navigation.PushAsync(new QuestionPage(new Question()));
};
customMap.CustomPins = new List<CustomPin> { pin };
customMap.Pins.Add(pin);
var json = JsonConvert.SerializeObject(new { X = pin.Position.Latitude, Y = pin.Position.Longitude });
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var result = await client.PostAsync("URL to points", content);
if (result.StatusCode == HttpStatusCode.Created)
{
await DisplayAlert("Komunikat", "Dodanie puntku przebiegło pomyślnie", "Anuluj");
}
}
private void OnNewRouteClicked(object sender, EventArgs e)
{
}
}
I wrote an example and hope it will help you. In the OnNewRouteClicked method, get all the points which routeId = 1 and draw a polyline with them:
public partial class MainPage : ContentPage
{
List<Points> myPoints { get; set; }
Routes myRoute { get; set; }
public MainPage()
{
InitializeComponent();
//Some data you get from your apis
myRoute = new Routes() { Id = 1 };
myPoints = new List<Points>();
myPoints.Add(new Points() { Id = 1, X = 55.6666, Y = 66.4444, RouteId = 1 }); ;
myPoints.Add(new Points() { Id = 2, X = 52.6666, Y = 68.4444, RouteId = 1 }); ;
myPoints.Add(new Points() { Id = 3, X = 53.6666, Y = 62.4444, RouteId = 1 }); ;
myPoints.Add(new Points() { Id = 1, X = 55.6666, Y = 61.4444, RouteId = 2 }); ;
myPoints.Add(new Points() { Id = 2, X = 51.6666, Y = 65.4444, RouteId = 2 }); ;
myPoints.Add(new Points() { Id = 4, X = 54.6666, Y = 67.4444, RouteId = 1 }); ;
myPoints.Add(new Points() { Id = 5, X = 59.6666, Y = 69.4444, RouteId = 1 }); ;
}
private void OnNewRouteClicked(object sender, EventArgs e)
{
List<Position> positions = new List<Position>();
//Get all the points which RouteId = 1
foreach (var item in myPoints)
{
Points tempPoint = item as Points;
if (tempPoint.RouteId == myRoute.Id)
{
Position tempPosition = new Position(tempPoint.X,tempPoint.Y);
positions.Add(tempPosition);
}
}
//your map
Map map = new Map
{
// ...
};
// instantiate a polyline
Polyline polyline = new Polyline
{
StrokeColor = Color.Blue,
StrokeWidth = 12,
};
//add your positions to polyline.Geopath
foreach (var item in positions)
{
polyline.Geopath.Add(item);
}
// add the polyline to the map's MapElements collection
map.MapElements.Add(polyline);
}
}
public class Routes
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class Points
{
public int Id { get; set; }
public double X { get; set; }
public double Y { get; set; }
public int RouteId { get; set; }
}
Related
I have some data in activity which I want to get it in RoutingSlipCompleted consume method. I know we can send data with CompletedWithVariables from a activity to b activity. But I was wondering how it is possible to get data from activity in RoutingSlipCompleted. so this is my activity:
public class CheckInventoryActivity : IActivity<ICheckInventoryRequest, CheckInventoryRequestCompensate>
{
private readonly IInventoryService _inventoryService;
private readonly IEndpointNameFormatter _formatter;
public CheckInventoryActivity(IInventoryService inventoryService, IEndpointNameFormatter formatter)
{
_inventoryService = inventoryService;
_formatter = formatter;
}
public async Task<ExecutionResult> Execute(ExecuteContext<ICheckInventoryRequest> context)
{
CheckInventoryRequest model = new CheckInventoryRequest()
{
PartCode = context.Arguments.PartCode
};
var response = await _inventoryService.CheckInventory(model);
var checkInventoryResponse = new CheckInventoryResponse()
{
PartCode = response.Data.PartCode ?? model.PartCode,
Id = response.Data.Id ?? 0,
InventoryCount = response.Data.InventoryCount ?? 0
};
var checkInventoryCustomActionResult = new CustomActionResult<CheckInventoryResponse>()
{
Data = checkInventoryResponse,
IsSuccess = true,
ResponseDesc = "success",
ResponseType = 0
};
var result = response.IsSuccess;
if (!result)
return context.CompletedWithVariables<CheckInventoryRequestCompensate>(
new
{
Result = result,
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
}, new
{
Result = result,
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
});
var queueName = _formatter.ExecuteActivity<CallSuccessActivity, ISuccessRequest>();
var uri = new Uri($"queue:{queueName}");
return context.ReviseItinerary(x => x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
}));
}
so by the following line of codes I can get data in CallSuccessActivity:
return context.ReviseItinerary(x => x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
}));
}
so I can get this data here:
public class CallSuccessActivity : IExecuteActivity<ISuccessRequest>
{
private readonly IRequestClient<ISuccessRequest> _requestClient;
public CallSuccessActivity(IRequestClient<ISuccessRequest> requestClient)
{
_requestClient = requestClient;
}
public async Task<ExecutionResult> Execute(ExecuteContext<ISuccessRequest> context)
{
var iModel = context.Arguments;
var model = new SuccessRequest()
{
LogDate = iModel.LogDate,
MethodName = iModel.MethodName,
CheckInventoryCustomActionResult = iModel.CheckInventoryCustomActionResult
};
//CustomActionResult< CheckInventoryResponse > CheckInventoryResponse = new ();
var rabbitResult = await _requestClient.GetResponse<CustomActionResult<SuccessResponse>>(model);
return context.Completed();
}
}
I want to get this iModel.CheckInventoryCustomActionResult in RoutingSlipCompleted :
public async Task Consume(ConsumeContext<RoutingSlipCompleted> context)
{
var requestId =
context.Message.GetVariable<Guid?>(nameof(ConsumeContext.RequestId));
var checkInventoryResponseModel = context.Message.Variables["CheckInventoryResponse"];
var responseAddress =
context.Message.GetVariable<Uri>(nameof(ConsumeContext.ResponseAddress));
var request =
context.Message.GetVariable< ICheckInventoryRequest > ("Model");
throw new NotImplementedException();
}
Instead of putting the value into the activity arguments, add it as a variable:
return context.ReviseItinerary(x =>
{
x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity"
});
x.AddVariable("CheckInventoryCustomActionResult", checkInventoryCustomActionResult);
});
Hi there i would like to let customers type a category name and get some search results. Currently when you type a category name it says no results.
public ActionResult AdvanceSearch(SearchModel model, CatalogPagingFilteringModel command)
{
//'Continue shopping' URL
_genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
SystemCustomerAttributeNames.LastContinueShoppingPage,
_webHelper.GetThisPageUrl(false),
_storeContext.CurrentStore.Id);
if (model == null)
model = new SearchModel();
var searchTerms = model.q;
if (searchTerms == null)
searchTerms = "";
searchTerms = searchTerms.Trim();
//sorting
PrepareSortingOptions(model.PagingFilteringContext, command);
//view mode
PrepareViewModes(model.PagingFilteringContext, command);
//page size
PreparePageSizeOptions(model.PagingFilteringContext, command,
_catalogSettings.SearchPageAllowCustomersToSelectPageSize,
_catalogSettings.SearchPagePageSizeOptions,
_catalogSettings.SearchPageProductsPerPage);
string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY,
_workContext.WorkingLanguage.Id,
string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var categories = _cacheManager.Get(cacheKey, () =>
{
var categoriesModel = new List<SearchModel.CategoryModel>();
//all categories
var allCategories = _categoryService.GetAllCategories(storeId: _storeContext.CurrentStore.Id);
foreach (var c in allCategories)
{
//generate full category name (breadcrumb)
string categoryBreadcrumb = "";
var breadcrumb = c.GetCategoryBreadCrumb(allCategories, _aclService, _storeMappingService);
for (int i = 0; i <= breadcrumb.Count - 1; i++)
{
categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name);
if (i != breadcrumb.Count - 1)
categoryBreadcrumb += " >> ";
}
categoriesModel.Add(new SearchModel.CategoryModel
{
Id = c.Id,
Breadcrumb = categoryBreadcrumb
});
}
return categoriesModel;
});
if (categories.Any())
{
//first empty entry
model.AvailableCategories.Add(new SelectListItem
{
Value = "0",
Text = _localizationService.GetResource("Common.All")
});
//all other categories
foreach (var c in categories)
{
model.AvailableCategories.Add(new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Breadcrumb,
Selected = model.cid == c.Id
});
}
}
IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);
// only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
if (Request.Params["q"] != null)
{
if (searchTerms.Length < _catalogSettings.ProductSearchTermMinimumLength)
{
model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
}
else
{
var categoryIds = new List<int>();
int manufacturerId = 0;
decimal? minPriceConverted = null;
decimal? maxPriceConverted = null;
bool searchInDescriptions = false;
int vendorId = 0;
if (model.adv)
{
//advanced search
var categoryId = model.cid;
if (categoryId > 0)
{
categoryIds.Add(categoryId);
if (model.isc)
{
//include subcategories
categoryIds.AddRange(GetChildCategoryIds(categoryId));
}
}
manufacturerId = model.mid;
//min price
if (!string.IsNullOrEmpty(model.pf))
{
decimal minPrice;
if (decimal.TryParse(model.pf, out minPrice))
minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency);
}
//max price
if (!string.IsNullOrEmpty(model.pt))
{
decimal maxPrice;
if (decimal.TryParse(model.pt, out maxPrice))
maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency);
}
if (model.asv)
vendorId = model.vid;
searchInDescriptions = model.sid;
}
//var searchInProductTags = false;
var searchInProductTags = searchInDescriptions;
//products
products = _productService.SearchProducts(
categoryIds: categoryIds,
manufacturerId: manufacturerId,
storeId: _storeContext.CurrentStore.Id,
visibleIndividuallyOnly: true,
priceMin: minPriceConverted,
priceMax: maxPriceConverted,
keywords: searchTerms,
//searchDescriptions: searchInDescriptions,
searchProductTags: searchInProductTags,
searchSku: true,
languageId: _workContext.WorkingLanguage.Id,
orderBy: (ProductSortingEnum)command.OrderBy,
pageIndex: command.PageNumber - 1,
pageSize: command.PageSize,
vendorId: vendorId);
model.Products = PrepareProductOverviewModels(products).ToList();
model.NoResults = !model.Products.Any();
//search term statistics
if (!String.IsNullOrEmpty(searchTerms))
{
var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id);
if (searchTerm != null)
{
searchTerm.Count++;
_searchTermService.UpdateSearchTerm(searchTerm);
}
else
{
searchTerm = new SearchTerm
{
Keyword = searchTerms,
StoreId = _storeContext.CurrentStore.Id,
Count = 1
};
_searchTermService.InsertSearchTerm(searchTerm);
}
}
//event
_eventPublisher.Publish(new ProductSearchEvent
{
SearchTerm = searchTerms,
SearchInDescriptions = searchInDescriptions,
CategoryIds = categoryIds,
ManufacturerId = manufacturerId,
WorkingLanguageId = _workContext.WorkingLanguage.Id,
VendorId = vendorId
});
}
}
model.PagingFilteringContext.LoadPagedList(products);
return View(model);
}
A public action method 'AdvanceSearch' was not found on controller 'Nop.Web.Controllers.CatalogController'.
In my ASP.NET project, I add a new array item with the help of query string. once the array item added, my client reload the browser,. so the same item add another time. It happens each reload timing.
but i don't want this. any possible to stop this browser reload or stop the same array item?
my url is -
51402/ItemGrid.aspx?id=3035
then id=3035 item added to the array.
My Code in page load event
string query ="";
int array_no;
if (Convert.ToUInt32(GlobalClass.GlobalarrayNo.ToString()) == 0)
{
array_no = 0;
Array.Clear(roomno, 0, roomno.Length);
}
else
{
array_no = Convert.ToInt32(GlobalClass.GlobalarrayNo.ToString());
}
id = Convert.ToInt32(Request.QueryString["id"]);
if (!Page.IsPostBack)
{
// ******* Happy Status ************
decimal happyfromtime = 0;
string happyper="";
string happytotime = "";
query = "SELECT Parameters_Parameter3,Parameters_Parameter2,Parameters_Parameter1,Parameters_Parameter4 FROM MCS_Parameters WHERE Parameters_TYPE ='HAPHOU'";
MySqlConnection connection = new MySqlConnection(GlobalClass.GlobalConnString.ToString());
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
happyfromtime= Convert.ToDecimal(Reader[0].ToString());
happyper=Reader[1].ToString();
happystatus= Convert.ToInt32(Reader[2].ToString());
happytotime = Reader[3].ToString();
}
connection.Close();
string t = GlobalClass.GlobalserverTime.ToString();
t= t.Substring(0,5);
t = t.Replace(":",".");
//ALLTRIM(CurCate.Fb_Item_Creation_HappyhoursStatus)='Yes'
if ((Convert.ToDecimal(t) > Convert.ToDecimal(happyfromtime)) && (Convert.ToDecimal(t) < Convert.ToDecimal(happytotime)) && (happystatus == 1))
{
tHappy_Status = 1;
}
if (GlobalClass.GlobalservedAt == "RST")
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_RestaurantPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus,a.Fb_Item_Creation_HappyhoursStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
else if (GlobalClass.GlobalservedAt == "BAR")
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_BarPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus,a.Fb_Item_Creation_HappyhoursStatus,a.Fb_Item_Creation_HappyhoursStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
else
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_RoomPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
connection = new MySqlConnection(GlobalClass.GlobalConnString.ToString());
command = new MySqlCommand(query, connection);
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
roomno[array_no, 0] = Reader[0].ToString(); // Fb_Item_Creation_ItemDescription
if (GlobalClass.GlobalopenCode == "OPEN")
{
roomno[array_no, 0] = GlobalClass.GlobalopenDes.ToString(); // Fb_Item_Creation_ItemDescription
roomno[array_no, 1] = GlobalClass.GlobalopenRate.ToString(); // Fb_Item_Creation_RoomPrice
roomno[array_no, 2] = GlobalClass.GlobalopenQty.ToString(); // Qty
roomno[array_no, 3] = Reader[2].ToString(); // Fb_Item_Creation_ItemCode
roomno[array_no, 4] = Reader[3].ToString(); // Fb_Item_Creation_TaxStatus
roomno[array_no, 5] = Reader[4].ToString(); // Fb_Item_Creation_VatPercentage
roomno[array_no, 6] = Reader[5].ToString(); // Fb_Item_Creation_ServicechargeStatus
roomno[array_no, 7] = Reader[6].ToString(); // Fb_Item_Creation_SurchargeStatus
roomno[array_no, 8] = Reader[7].ToString(); // Fb_Item_Creation_DiscountStatus
roomno[array_no, 9] = Reader[8].ToString(); // FB_Item_ID
roomno[array_no, 10] = Reader[9].ToString(); // Fb_Category_Stock
roomno[array_no, 11] = Reader[10].ToString(); // Fb_Category_Name
roomno[array_no, 12] = Reader[1].ToString(); // Total = rate * qty
roomno[array_no, 13] = Reader[11].ToString(); //Fb_Item_Creation_ModifierStatus
roomno[array_no, 14] = ""; //Fb_Kot_Item_TouchLine
roomno[array_no, 15] = ""; // UserModifier
roomno[array_no, 16] = Reader[12].ToString(); // HappyHours
array_no++;
GlobalClass.GlobalarrayNo = array_no;
}
else if (roomno[array_no, 0] == "OPEN")
{
Response.Redirect("OpenItem.aspx" + "?id=" + id);
}
else
{
roomno[array_no, 1] = Reader[1].ToString(); // Fb_Item_Creation_RoomPrice
roomno[array_no, 2] = "1"; // Qty
roomno[array_no, 3] = Reader[2].ToString(); // Fb_Item_Creation_ItemCode
roomno[array_no, 4] = Reader[3].ToString(); // Fb_Item_Creation_TaxStatus
roomno[array_no, 5] = Reader[4].ToString(); // Fb_Item_Creation_VatPercentage
roomno[array_no, 6] = Reader[5].ToString(); // Fb_Item_Creation_ServicechargeStatus
roomno[array_no, 7] = Reader[6].ToString(); // Fb_Item_Creation_SurchargeStatus
roomno[array_no, 8] = Reader[7].ToString(); // Fb_Item_Creation_DiscountStatus
roomno[array_no, 9] = Reader[8].ToString(); // FB_Item_ID
roomno[array_no, 10] = Reader[9].ToString(); // Fb_Category_Stock
roomno[array_no, 11] = Reader[10].ToString(); // Fb_Category_Name
roomno[array_no, 12] = Reader[1].ToString(); // Total = rate * qty
roomno[array_no, 13] = Reader[11].ToString(); //Fb_Item_Creation_ModifierStatus
roomno[array_no, 14] = ""; //Fb_Kot_Item_TouchLine
roomno[array_no, 15] = ""; // UserModifier
roomno[array_no, 16] = Reader[12].ToString(); // HappyHours
if ((tHappy_Status == 1) && (roomno[array_no, 16].ToString()=="Yes"))
{
roomno[array_no, 8] = "Yes";
}
array_no++;
GlobalClass.GlobalarrayNo = array_no;
//var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
//nameValues.Set("sortBy", "4");
//string url = Request.Url.AbsolutePath;
//string updatedQueryString = "?" + nameValues.ToString();
//Response.Redirect(url + updatedQueryString);
}
}
connection.Close();
ViewState["btn"] = "1";
ViewState["tot"] = "0";
ViewState["happystatus"] = happystatus;
btn_click = Convert.ToInt32(ViewState["btn"].ToString());
int len = array_no;
while (len > 8)
{
len = len - 8;
tot++;
}
if (len != 0) tot++;
ViewState["tot"] = tot;
fun();
//CreatingTmpModdbf1();
// Modifier Text
int seq = Convert.ToInt32(Request.QueryString["seq"]);
string text = Request.QueryString["text"];
if (text != null)
{
roomno[seq - 1, 15] = text;
}
}
!postback is not help to avoid my problem.
static class GlobalClass
{
private static string myConnString1 = "";
private static int userId = 0;
private static string userName = "";
private static int outletId = 0;
private static int itemGroupId = 0;
private static DateTime serverDate;
private static string serverTime = "";
private static string tableName = "";
private static string serverdAt = "";
private static int arrayNo = 0;
private static int waiterId = 0;
private static int covers = 0;
private static string kotno = "";
public static string GlobalConnString
{
get { return myConnString1; }
set { myConnString1 = value; }
}
public static int GlobaluserId
{
get { return userId;}
set { userId = value; }
}
public static string GlobaluserName
{
get { return userName; }
set { userName = value; }
}
public static int GlobaloutletId
{
get { return outletId; }
set { outletId = value; }
}
public static DateTime GlobalserverDate
{
get { return serverDate; }
set { serverDate = value; }
}
public static string GlobalserverTime
{
get { return serverTime; }
set { serverTime = value; }
}
public static string GlobaltableName
{
get { return tableName; }
set { tableName = value; }
}
public static int GlobalitemGroupId
{
get { return itemGroupId; }
set { itemGroupId = value; }
}
public static string GlobalservedAt
{
get { return serverdAt; }
set { serverdAt = value; }
}
public static int GlobalarrayNo
{
get { return arrayNo; }
set { arrayNo = value; }
}
public static int GlobalwaiterId
{
get { return waiterId; }
set { waiterId = value; }
}
public static int Globalcovers
{
get { return covers; }
set { covers = value; }
}
public static string GlobalkotNo
{
get { return kotno ; }
set { kotno = value; }
}
public static string staffId = "";
public static string staffCategoryId = "";
public static string GlobalstaffId
{
get { return staffId; }
set { staffId = value; }
}
public static string GlobalstaffCategoryId
{
get { return staffCategoryId; }
set { staffCategoryId = value; }
}
public static string openCode = "";
public static string openDes = "";
public static string GlobalopenCode
{
get { return openCode; }
set { openCode = value; }
}
public static string GlobalopenDes
{
get { return openDes; }
set { openDes = value; }
}
public static string openQty = "";
public static string openRate = "";
public static string GlobalopenQty
{
get { return openQty; }
set { openQty = value; }
}
public static string GlobalopenRate
{
get { return openRate; }
set { openRate = value; }
}
}
I assume that your array is static/shared. Static variables are shared across the whole app domain and all threads. Hence every user uses the same variable.
Don't use static variables therefor, instead of persisting the array you should use the querystring again.
If this was a wrong assumption you should show us your code
After adding item you can redirect to another page. For example 51402/ItemGrid.aspx
Also using get request to save/edit/delete data is not good idea, better use post.
If you are adding the item to the Array within Page_Load, you may want to wrap the code that adds the item in the following:
If Not Page.IsPostBack Then
//Your array item adding code here
End If
This will prevent the item adding again if the user refreshes the page. Though, I'd like to echo Tim and say that if I assumed incorrectly, you should post your code.
Hello everyone i am working on a project in which i have to export some data into a ppt using openxml on button click.Here is my code for the aspx page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
using DocumentFormat.Extensions1;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
namespace TableInPPT
{
public partial class _Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string templateFile = Server.MapPath("~/Template/Sample.potm");
string presentationFile = Server.MapPath("~/Template/SmapleNew.pptx");
PotxToPptx(templateFile, presentationFile);
//using (PresentationDocument themeDocument = PresentationDocument.Open(templateFile, false))
using (PresentationDocument prstDoc = PresentationDocument.Open(presentationFile, true))
{
AddImage(prstDoc);
AddTable(prstDoc);
}
string itemname = "SmapleNew.pptx";
Response.Clear();
Response.ContentType = "pptx";
Response.AddHeader("Content-Disposition", "attachment; filename=" + itemname + "");
Response.BinaryWrite(System.IO.File.ReadAllBytes(presentationFile));
Response.Flush();
Response.End();
}
private void PotxToPptx(string templateFile, string presentationFile)
{
MemoryStream presentationStream = null;
using (Stream tplStream = File.Open(templateFile, FileMode.Open, FileAccess.Read))
{
presentationStream = new MemoryStream((int)tplStream.Length);
tplStream.Copy(presentationStream);
presentationStream.Position = 0L;
}
using (PresentationDocument pptPackage = PresentationDocument.Open(presentationStream, true))
{
pptPackage.ChangeDocumentType(DocumentFormat.OpenXml.PresentationDocumentType.Presentation);
PresentationPart presPart = pptPackage.PresentationPart;
presPart.PresentationPropertiesPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
new Uri(templateFile, UriKind.RelativeOrAbsolute));
presPart.Presentation.Save();
}
File.WriteAllBytes(presentationFile, presentationStream.ToArray());
}
private void AddTable(PresentationDocument prstDoc)
{
// Add one slide
Slide slide = prstDoc.PresentationPart.InsertSlide1("Custom Layout", 2);
Shape tableShape = slide.CommonSlideData.ShapeTree.ChildElements.OfType<Shape>()
.Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder").SingleOrDefault();
if (tableShape == null) return;
// Create Graphic Frame
OpenXmlCompositeElement gElement = GetGraphicFrame(tableShape);
// Create a (6x3)Table
ODrawing.Table openXmlTable = GetSmapleTable();
// add table to graphic element
gElement.GetFirstChild<ODrawing.Graphic>().GetFirstChild<ODrawing.GraphicData>().Append(openXmlTable);
slide.CommonSlideData.ShapeTree.Append(gElement);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(tableShape);
prstDoc.PresentationPart.Presentation.Save();
}
private void AddImage(PresentationDocument prstDoc)
{
string imgpath = Server.MapPath("~/Template/xxxx.jpg");
Slide slide = prstDoc.PresentationPart.InsertSlide("Title and Content", 2);
Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
(new NonVisualDrawingProperties() { Id = 2, Name = "Title" },
new NonVisualShapeDrawingProperties(new ODrawing.ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
titleShape.ShapeProperties = new ShapeProperties();
// Specify the text of the title shape.
titleShape.TextBody = new TextBody(new ODrawing.BodyProperties(),
new ODrawing.ListStyle(),
new ODrawing.Paragraph(new ODrawing.Run(new ODrawing.Text() { Text = "Trade Promotion Graph " })));
Shape shape = slide.CommonSlideData.ShapeTree.Elements<Shape>().FirstOrDefault(
sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Content Placeholder 2".ToLower()));
Picture pic = slide.AddPicture(shape, imgpath);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(shape);
slide.Save();
prstDoc.PresentationPart.Presentation.Save();
}
private ODrawing.Table GetSmapleTable()
{
ODrawing.Table table = new ODrawing.Table();
ODrawing.TableProperties tableProperties = new ODrawing.TableProperties();
ODrawing.TableStyleId tableStyleId = new ODrawing.TableStyleId();
tableStyleId.Text = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}";
//tableStyleId.Text = "{D27102A9-8310-4765-A935-A1911B00CA55}";
tableProperties.Append(tableStyleId);
ODrawing.TableGrid tableGrid = new ODrawing.TableGrid();
ODrawing.GridColumn gridColumn1 = new ODrawing.GridColumn() { Width = 2600000L};
ODrawing.GridColumn gridColumn2 = new ODrawing.GridColumn() { Width = 2600000L };
//ODrawing.GridColumn gridColumn3 = new ODrawing.GridColumn() { Width = 1071600L };
//ODrawing.GridColumn gridColumn4 = new ODrawing.GridColumn() { Width = 1571600L };
//ODrawing.GridColumn gridColumn5 = new ODrawing.GridColumn() { Width = 771600L };
//ODrawing.GridColumn gridColumn6 = new ODrawing.GridColumn() { Width = 1071600L };
tableGrid.Append(gridColumn1);
tableGrid.Append(gridColumn2);
//tableGrid.Append(gridColumn3);
//tableGrid.Append(gridColumn4);
//tableGrid.Append(gridColumn5);
//tableGrid.Append(gridColumn6);
table.Append(tableProperties);
table.Append(tableGrid);
for (int row = 1; row <= 5; row++)
{
string text1 = "PARAMETERS";
string text2="VALUES";
if (row == 2)
{
text1 =Label1.Text ;
text2 = TextBox1.Text;
}
if (row == 3)
{
text1 = Label2.Text;
text2 = TextBox2.Text;
}
if (row == 4)
{
text1 = Label3.Text;
text2 = TextBox3.Text;
}
if (row == 5)
{
text1 = Label4.Text;
text2 = TextBox4.Text;
}
ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000},
new ODrawing.Text(text1)))),
new ODrawing.TableCellProperties()));
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000 },
new ODrawing.Text(text2)))),
new ODrawing.TableCellProperties()));
ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
schemeColor.Append(luminanceModulation);
solidFill.Append(schemeColor);
table.Append(tableRow);
}
//for (int row = 1; row <= 3; row++)
//{
// ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
// for (int column = 1; column <= 6; column++)
// {
// ODrawing.TableCell tableCell = new ODrawing.TableCell();
// TextBody textBody = new TextBody() { BodyProperties = new ODrawing.BodyProperties(), ListStyle = new ODrawing.ListStyle() };
// ODrawing.Paragraph paragraph = new ODrawing.Paragraph();
// ODrawing.Run run = new ODrawing.Run();
// ODrawing.RunProperties runProperties = new ODrawing.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
// ODrawing.Text text = new ODrawing.Text();
// text.Text = "Smaple Text";
// run.Append(runProperties);
// run.Append(text);
// ODrawing.EndParagraphRunProperties endParagraphRunProperties = new ODrawing.EndParagraphRunProperties() { Language = "en-US", Dirty = false };
// paragraph.Append(run);
// paragraph.Append(endParagraphRunProperties);
// textBody.Append(paragraph);
// ODrawing.TableCellProperties tableCellProperties = new ODrawing.TableCellProperties();
// ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
// ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
// ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
// schemeColor.Append(luminanceModulation);
// solidFill.Append(schemeColor);
// tableCellProperties.Append(solidFill);
// tableCell.Append(textBody);
// tableCell.Append(tableCellProperties);
// tableRow.Append(tableCell);
// if (column == 1 && row == 1)
// {
// tableRow.Append(CreateTextCell("category"));
// }
// }
// }
return table;
}
static ODrawing.TableCell CreateTextCell(string text)
{
ODrawing.TableCell tc = new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.Text(text)))),
new ODrawing.TableCellProperties());
return tc;
}
private static OpenXmlCompositeElement GetGraphicFrame(Shape refShape)
{
GraphicFrame graphicFrame = new GraphicFrame();
int contentPlaceholderCount = 0;
UInt32Value graphicFrameId = 1000;
NonVisualGraphicFrameProperties nonVisualGraphicFrameProperties = new NonVisualGraphicFrameProperties();
NonVisualDrawingProperties nonVisualDrawingProperties = new NonVisualDrawingProperties()
{
Id = ++graphicFrameId,
Name = "Table" + contentPlaceholderCount.ToString(),
};
NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties = new NonVisualGraphicFrameDrawingProperties();
ODrawing.GraphicFrameLocks graphicFrameLocks = new ODrawing.GraphicFrameLocks() { NoGrouping = true };
nonVisualGraphicFrameDrawingProperties.Append(graphicFrameLocks);
ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
PlaceholderShape placeholderShape = new PlaceholderShape() { Index = graphicFrameId };
applicationNonVisualDrawingProperties.Append(placeholderShape);
nonVisualGraphicFrameProperties.Append(nonVisualDrawingProperties);
nonVisualGraphicFrameProperties.Append(nonVisualGraphicFrameDrawingProperties);
nonVisualGraphicFrameProperties.Append(applicationNonVisualDrawingProperties);
Transform transform = new Transform()
{
Offset = new ODrawing.Offset() { X = refShape.ShapeProperties.Transform2D.Offset.X, Y = refShape.ShapeProperties.Transform2D.Offset.Y },
Extents = new ODrawing.Extents() { Cx = refShape.ShapeProperties.Transform2D.Extents.Cx, Cy = refShape.ShapeProperties.Transform2D.Extents.Cy }
};
ODrawing.Graphic graphic = new ODrawing.Graphic();
ODrawing.GraphicData graphicData = new ODrawing.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/table" };
graphic.Append(graphicData);
graphicFrame.Append(nonVisualGraphicFrameProperties);
graphicFrame.Append(transform);
graphicFrame.Append(graphic);
return graphicFrame;
}
}
}
Please note that the template used is a sample template containing two slides only i.e. one title slide and one more blank side with a wordart having some random text written on it.
Also the table is filled with data from 4 textboxes present on the aspx page.
And here is the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using Drawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
namespace DocumentFormat.Extensions1
{
public static class Extensions1
{
internal static Slide InsertSlide(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
public static Slide InsertSlide1(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideMasterPart smPart = presentationPart.SlideMasterParts.First();
SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
//SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
sPart.AddPart<SlideLayoutPart>(slPart);
sPart.Slide.CommonSlideData = (CommonSlideData)smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName)).SlideLayout.CommonSlideData.Clone();
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
internal static int ReorderSlides(PresentationPart presentationPart, int currentSlidePosition, int newPosition)
{
int returnValue = -1;
if (newPosition == currentSlidePosition) { return returnValue; }
int slideCount = presentationPart.SlideParts.Count();
if (slideCount == 0) { return returnValue; }
int maxPosition = slideCount - 1;
CalculatePositions(ref currentSlidePosition, ref newPosition, maxPosition);
if (newPosition != currentSlidePosition)
{
DocumentFormat.OpenXml.Presentation.Presentation presentation = presentationPart.Presentation;
SlideIdList slideIdList = presentation.SlideIdList;
SlideId sourceSlide = (SlideId)(slideIdList.ChildElements[currentSlidePosition]);
SlideId targetSlide = (SlideId)(slideIdList.ChildElements[newPosition]);
sourceSlide.Remove();
if (newPosition > currentSlidePosition)
{
slideIdList.InsertAfter(sourceSlide, targetSlide);
}
else
{
slideIdList.InsertBefore(sourceSlide, targetSlide);
}
returnValue = newPosition;
}
presentationPart.Presentation.Save();
return returnValue;
}
private static void CalculatePositions(ref int originalPosition, ref int newPosition, int maxPosition)
{
if (originalPosition < 0)
{
originalPosition = maxPosition;
}
if (newPosition < 0)
{
newPosition = maxPosition;
}
if (originalPosition > maxPosition)
{
originalPosition = maxPosition;
}
if (newPosition > maxPosition)
{
newPosition = maxPosition;
}
}
private static Slide GetSlideByRelationshipId(PresentationPart presentationPart, DocumentFormat.OpenXml.StringValue relId)
{
SlidePart slidePart = presentationPart.GetPartById(relId) as SlidePart;
if (slidePart != null)
{
return slidePart.Slide;
}
else
{
return null;
}
}
internal static Picture AddPicture(this Slide slide, Shape referingShape, string imageFile)
{
Picture picture = new Picture();
string embedId = string.Empty;
UInt32Value picId = 10001U;
string name = string.Empty;
if (slide.Elements<Picture>().Count() > 0)
{
picId = ++slide.Elements<Picture>().ToList().Last().NonVisualPictureProperties.NonVisualDrawingProperties.Id;
}
name = "image" + picId.ToString();
embedId = "rId" + (slide.Elements<Picture>().Count() + 915).ToString(); // some value
NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties()
{
NonVisualDrawingProperties = new NonVisualDrawingProperties() { Name = name, Id = picId, Title = name },
NonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties() { PictureLocks = new Drawing.PictureLocks() { NoChangeAspect = true } },
ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties() { UserDrawn = true }
};
BlipFill blipFill = new BlipFill() { Blip = new Drawing.Blip() { Embed = embedId } };
Drawing.Stretch stretch = new Drawing.Stretch() { FillRectangle = new Drawing.FillRectangle() };
blipFill.Append(stretch);
ShapeProperties shapeProperties = new ShapeProperties()
{
Transform2D = new Drawing.Transform2D()
{
Offset = new Drawing.Offset() { X = 1554691, Y = 1600200 },
Extents = new Drawing.Extents() { Cx = 6034617, Cy = 4525963 }
}
};
Drawing.PresetGeometry presetGeometry = new Drawing.PresetGeometry() { Preset = Drawing.ShapeTypeValues.Rectangle };
Drawing.AdjustValueList adjustValueList = new Drawing.AdjustValueList();
presetGeometry.Append(adjustValueList);
shapeProperties.Append(presetGeometry);
picture.Append(nonVisualPictureProperties);
picture.Append(blipFill);
picture.Append(shapeProperties);
slide.CommonSlideData.ShapeTree.Append(picture);
// Add Image part
slide.AddImagePart(embedId, imageFile);
slide.Save();
return picture;
}
private static void AddImagePart(this Slide slide, string relationshipId, string imageFile)
{
ImagePart imgPart = slide.SlidePart.AddImagePart(GetImagePartType(imageFile), relationshipId);
using (FileStream imgStream = File.Open(imageFile, FileMode.Open))
{
imgPart.FeedData(imgStream);
}
}
private static ImagePartType GetImagePartType(string imageFile)
{
string[] imgFileSplit = imageFile.Split('.');
string imgExtension = imgFileSplit.ElementAt(imgFileSplit.Count() - 1).ToString().ToLower();
if (imgExtension.Equals("jpg"))
imgExtension = "jpeg";
return (ImagePartType)Enum.Parse(typeof(ImagePartType), imgExtension, true);
}
public static void Copy(this Stream source, Stream target)
{
if (source != null)
{
MemoryStream mstream = source as MemoryStream;
if (mstream != null) mstream.WriteTo(target);
else
{
byte[] buffer = new byte[2048];
int length = buffer.Length, size;
while ((size = source.Read(buffer, 0, length)) != 0)
target.Write(buffer, 0, size);
}
}
}
}
}
Now here are my queries:
1.In the aspx page if i try to replace the templateFile with my own template(same as the sample)it gives me an error "Object reference not set to an instance of an object" at this line Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder") under AddTable.Otherwise it works fine.
2.Also in the second slide i am getting the required table but with the word "image" written 5 times on top of the page.
3.Also in the powerpoint file generated,the template style is not displayed on the slides except the first and the last slide(i.e the slides which are there in the template).
Thank you.
I am trying to bind generic list to DropDownList an i am not sure how to continue.
here is my code:
protected void Page_Load(object sender, EventArgs e)
{
List<Paths> paths = new List<Paths>();
paths = GetOriginalPaths();
DropDownList1.DataSource = paths;
DropDownList1.DataTextField = "orignalPathName";
DropDownList1.DataValueField = "orignalPathId";
DropDownList1.DataBind();
}
public class Paths
{
public string orignalPathName;
public int orignalPathId;
public string newPathName;
}
public static List<Paths> GetOriginalPaths()
{
return PrepareOriginalPathsData();
}
public static List<Paths> PrepareOriginalPathsData()
{
List<Paths> objPaths = new List<Paths> {
new Paths{orignalPathName = "comp1", orignalPathId= 1} ,
new Paths{orignalPathName = "comp1", orignalPathId= 1} ,
new Paths{orignalPathName = "comp1", orignalPathId= 1} ,
new Paths{orignalPathName = "comp2", orignalPathId= 2} ,
new Paths{orignalPathName = "comp3", orignalPathId= 3} ,
new Paths{orignalPathName = "comp4", orignalPathId= 4}
};
return objPaths;
}
public static List<Paths> GetNewPaths(int orignalPathId)
{
List<Paths> lstNewPaths = new List<Paths>();
Paths objnewPaths = null;
var newPath = (from np in PrepareNewPathsData() where np.orignalPathId == orignalPathId select new { newpathname = np.newPathName, orgId = np.orignalPathId });
foreach (var np in newPath)
{
objnewPaths = new Paths();
objnewPaths.orignalPathId = np.orgId;
objnewPaths.newPathName = np.newpathname;
lstNewPaths.Add(objnewPaths);
}
return lstNewPaths;
}
public static List<Paths> PrepareNewPathsData()
{
List<Paths> objNewPaths = new List<Paths> {
new Paths{newPathName = "part1", orignalPathId= 1} ,
new Paths{newPathName = "part1", orignalPathId= 1} ,
new Paths{newPathName = "part1", orignalPathId= 1} ,
new Paths{newPathName = "part3", orignalPathId= 2} ,
new Paths{newPathName = "part4", orignalPathId= 3} ,
new Paths{newPathName = "part5", orignalPathId= 4} ,
};
return objNewPaths;
}
Fix it!
I had to add this:
public class Paths
{
public string orignalPathName { get; set; }
public int orignalPathId { get; set; }
public string newPathName { get; set; }
}
Your problem might be from the bind prospective you might bind only if not post back!!
If(!Page.IsPostBack)
{
List<Paths> paths = new List<Paths>();
paths = GetOriginalPaths();
DropDownList1.DataSource = paths;
DropDownList1.DataTextField = "orignalPathName";
DropDownList1.DataValueField = "orignalPathId";
DropDownList1.DataBind();
}
What problem are you encountering exactly?
By the way, the DataValueField should be unique. Aas it is it could cause an issue either with the bind, or on post-back.