How to hide rows while editing a specific row from the user in gridview - sql

I have a web application which is connected to SQL server management studio.
I have one problem to finish my application.
In my gridview users are able to edit their own reservation, but once i reach update part for the gridview it shows me that the users are able to edit the other reservation and here are some images to show you the meaning of this:
1) this the code in my gridview events
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if ((row.Cells[9].Text.Trim()).Equals(HttpContext.Current.User.Identity.Name) == false)
{
//row.BackColor = Color.Red;
row.Cells[0].Controls.Clear();
}
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Label1.Text = "Changed";
GridViewRow selectedRow = GridView1.Rows[e.NewEditIndex];
foreach (GridViewRow row in GridView1.Rows)
{
int currentIndex = row.RowIndex;
if (currentIndex != e.NewEditIndex)
{
row.Visible = false;
}
}
}
}
2) this is to show you that user can edit only their own reservation
so how can i solve this ?

I have updated GridView's RowEditing event:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
// Bind Grid Again Here
}

Related

GridView: Get Index on Drop Event

How do I get the index or position where a GridViewItem is being dropped inside the OnDrop event of the GridView? As I have read around that it is possible with GridView.ItemContainerGenerator.ContainerFromItem(item) but for me ItemContainerGenerator is null.
This is my current code:
void gridMain_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
var item = e.Items.First();
var source = sender;
e.Data.Properties.Add("item", item);
e.Data.Properties.Add("source", sender);
}
void gridMain_Drop(object sender, DragEventArgs e)
{
var item = e.Data.Properties.Where(p => p.Key == "item").Single();
object source;
e.Data.Properties.TryGetValue("source", out source);
var s = ((GridView)source).ItemContainerGenerator.ContainerFromItem(item);
}
Any hint or suggestion will be really helpful.
Use GetPosition method of DragEventArgs to find the position where item was dropped and then calculate the actual index, see code snippet below for the handler. Similar question was asked here using this MSDN example as an answer (Scenario 3).
private void GridView_Drop(object sender, DragEventArgs e)
{
GridView view = sender as GridView;
// Get your data
var item = e.Data.Properties.Where(p => p.Key == "item").Single();
//Find the position where item will be dropped in the gridview
Point pos = e.GetPosition(view.ItemsPanelRoot);
//Get the size of one of the list items
GridViewItem gvi = (GridViewItem)view.ContainerFromIndex(0);
double itemHeight = gvi.ActualHeight + gvi.Margin.Top + gvi.Margin.Bottom;
//Determine the index of the item from the item position (assumed all items are the same size)
int index = Math.Min(view.Items.Count - 1, (int)(pos.Y / itemHeight));
// Call your viewmodel with the index and your data.
}
EDIT: Please, consider this as just a prototype. I tried it and it has worked properly, but you may revise it according to your scenario (tweak delay timeout, differentiate more TaskCompletionSource at once, etc.).
The idea is to start a task after Remove action to check whether the item was only removed, or reordered.
private async void observableCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
object removedItem = e.OldItems[0];
var reorderTask = NoticeReorderAsync(removedItem);
try
{
var task = await Task.WhenAny(reorderTask, Task.Delay(100));
if (reorderTask == task)
{
// removedItem was in fact reordered
Debug.WriteLine("reordered");
}
else
{
TryCancelReorder();
// removedItem was really removed
Debug.WriteLine("removedItem");
}
}
catch (TaskCanceledException ex)
{
Debug.WriteLine("removedItem (from exception)");
}
finally
{
tcs = null;
}
}
else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
object addedItem = e.NewItems[0];
bool added = NoticeAdd(addedItem);
if (added)
{
// addedItem was just added, not reordered
Debug.WriteLine("added");
}
}
}
TaskCompletionSource<object> tcs;
private void TryCancelReorder()
{
if (tcs != null)
{
tcs.TrySetCanceled();
tcs = null;
}
}
private Task NoticeReorderAsync(object removed)
{
TryCancelReorder();
tcs = new TaskCompletionSource<object>(removed);
return tcs.Task;
}
private bool NoticeAdd(object added)
{
if (tcs != null)
{
try
{
if (object.Equals(tcs.Task.AsyncState, added))
{
tcs.TrySetResult(added);
return false;
}
else
{
tcs.TrySetCanceled();
return true;
}
}
finally
{
tcs = null;
}
}
return true;
}

Show back button in charm settings with my privacy page in windows store apps

I have a code which show privacy policy URL in charm settings bar.But what I need is like when user clicks on the privacy policy link it should open another page in charm settings with a back button.How to do the same in the below code
private async void OpenPrivacyPolicy(IUICommand command)
{
Uri uri = new Uri("https://sites.google.com/site/mysite/");
await Windows.System.Launcher.LaunchUriAsync(uri);
}
Finally I figured out the solution,thanks to windows 8.1 Appsetting sample app . First of all add a settingsFlyout XAML page to your project.I added the privacy flyout code in my app's home page like this
protected override void OnNavigatedTo(NavigationEventArgs e)
{
SettingsPane.GetForCurrentView().CommandsRequested += onCommandsRequested;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
SettingsPane.GetForCurrentView().CommandsRequested -= onCommandsRequested;
}
void onCommandsRequested(SettingsPane settingsPane, SettingsPaneCommandsRequestedEventArgs e)
{
SettingsCommand defaultsCommand = new SettingsCommand("Privacy", "Privacy",
(handler) =>
{
Privacy sf = new Privacy();
sf.Show();
});
e.Request.ApplicationCommands.Add(defaultsCommand);
}
then in my Privacy.xaml page I added the following code
public Privacy()
{
this.InitializeComponent();
this.Loaded += (sender, e) =>
{
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += SettingsFlyout1_AcceleratorKeyActivated;
};
this.Unloaded += (sender, e) =>
{
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -= SettingsFlyout1_AcceleratorKeyActivated;
};
}
void SettingsFlyout1_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args)
{
// Only investigate further when Left is pressed
if (args.EventType == CoreAcceleratorKeyEventType.SystemKeyDown &&
args.VirtualKey == VirtualKey.Left)
{
var coreWindow = Window.Current.CoreWindow;
var downState = CoreVirtualKeyStates.Down;
bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState;
bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState;
bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState;
if (menuKey && !controlKey && !shiftKey)
{
args.Handled = true;
this.Hide();
}
}
}
Thanks for all the help everyone! And this code works!If anyone facing difficulty just hit me ;)

Improve software responsiveness when slider is manipulated in windows phone

I have a slider in my windows phone 7.1 project. When manipulated, this slider fires an event which starts a background worker to performs several trigonometric operations.
If I move the cursor on the slider, I have a certain delay in the response although I have implement background worker cancelAsync method in manipulationstarted event, I would like more responsiveness, how can I achieve this?
Code:
private void sliderCosinus_ManipulationStarted(object sender,ManipulationStartedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync(); // Cancel the asynchronous operation.
}
}
private void sldCosinus_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
try
{
Value = Convert.ToInt32(sldCosinus.Value) * 10;
}
catch
{
// errore message here
}
finally
{
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
else
{
Dispatcher.BeginInvoke(() => app.IsEffectApplied=TrigonometricTrans()
// TrigonomtriecTrans calculate sin and cosinus for every pixel in image
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// progress bar here
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
//this.tbProgress.Text = "Canceled!";
}
else if (!(e.Error == null))
{
//this.tbProgress.Text = ("Error: " + e.Error.Message);
}
else
{
DoubleBufferToScreen();
}
}

Detect which child control received a Pointer* event

I have a container control that is handling PointerPressed and PointerMoved events.
The container contains a set of buttons.
At the point of handling the event, how can I determine which button actually received it?
mainPage.AddHandler(PointerPressedEvent, new PointerEventHandler(pointerPressedHandler), true);
private void pointerPressedHandler(object sender, PointerRoutedEventArgs e)
{
var p = e.GetCurrentPoint(null); // maybe can be done using position info?
var s = e.OriginalSource as Border; // OriginalSource is a Border, not the Button, and I don't seem to be able to get to the Button from the Border
// todo - determine which button was clicked
}
This works:
private void pointerPressedHandler(object sender, PointerRoutedEventArgs e)
{
var p = e.GetCurrentPoint(null);
var elements = VisualTreeHelper.FindElementsInHostCoordinates(p.Position, mainPage, false);
Button foundButton;
foreach (var item in elements)
{
foundButton = item as Button;
if (foundButton != null)
{
System.Diagnostics.Debug.WriteLine("found button: " + foundButton.Name);
}
}
}

Add new Item and Edit Item in silverlight DataForm not correctly updating SharePoint List

I am trying to make a simple Silverlight application that will be hosted on a SharePoint site.
I am reading the information from the list "testlist" and I am trying to use a dataform control to edit, add and delete data from the list. I am able to delete just fine. When I try to add it adds a new entry with the data from the item previously viewed and I am unable to edit current Items whatsoever. Here is my code:
namespace SP2010
{
public partial class MainPage : UserControl
{
ClientContext context;
List customerList;
ListItemCollection allCustomers;
public MainPage()
{
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
InitializeComponent();
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = this;
context = new ClientContext(ApplicationContext.Current.Url);
customerList = context.Web.Lists.GetByTitle("testlist");
context.Load(customerList);
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =#"<View><Query></Query><RowLimit>1000</RowLimit></View>";
allCustomers = customerList.GetItems(camlQuery);
context.Load(allCustomers);
context.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(OnRequestSucceeded), new ClientRequestFailedEventHandler(OnRequestFailed));
}
private void OnRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
{
Dispatcher.BeginInvoke(DisplayListData);
}
private void OnRequestFailed(Object sender, ClientRequestFailedEventArgs args)
{
MessageBox.Show(args.ErrorDetails + " " + args.Message);
}
public ObservableCollection<SPCustomers> Printers
{
get
{
if (printers == null)
{
printers = new ObservableCollection<SPCustomers>();
foreach (ListItem item in allCustomers)
{
printers.Add(new SPCustomers
{
IPAddress = item["Title"].ToString(),
Make = item["make"].ToString(),
Model = item["model"].ToString(),
xCord = item["x"].ToString(),
yCord = item["y"].ToString(),
id = Convert.ToInt32(item["ID"].ToString())
});
}
}
return (printers);
}
}
private ObservableCollection<SPCustomers> printers;
private void DisplayListData()
{
dataForm1.DataContext = Printers;
}
private void dataForm1_EditEnded(object sender, DataFormEditEndedEventArgs e)
{
if (e.EditAction == DataFormEditAction.Commit)
{
if (dataForm1.IsItemChanged)
{
customerList = context.Web.Lists.GetByTitle("testlist");
SPCustomers printer = dataForm1.CurrentItem as SPCustomers;
ListItem items = customerList.GetItemById(printer.id);
items["Title"] = printer.IPAddress;
items["make"] = printer.Make;
items["model"] = printer.Model;
items["x"] = printer.xCord;
items["y"] = printer.yCord;
items.Update();
context.ExecuteQueryAsync(OnRequestSucceeded, OnRequestFailed);
}
}
}
private void dataForm1_AddingNewItem(object sender, DataFormAddingNewItemEventArgs e)
{
customerList = context.Web.Lists.GetByTitle("testlist");
SPCustomers printe = dataForm1.CurrentItem as SPCustomers;
ListItemCreationInformation itemcreationinfo = new ListItemCreationInformation();
ListItem items = customerList.AddItem(itemcreationinfo);
items["Title"] = printe.IPAddress;
items["make"] = printe.Make;
items["model"] = printe.Model;
items["x"] = printe.xCord;
items["y"] = printe.yCord;
items.Update();
context.ExecuteQueryAsync(OnRequestSucceeded, OnRequestFailed);
}
private void dataForm1_DeletingItem(object sender, System.ComponentModel.CancelEventArgs e)
{
SPCustomers printer = dataForm1.CurrentItem as SPCustomers;
ListItem oListItem = customerList.GetItemById(printer.id);
oListItem.DeleteObject();
context.ExecuteQueryAsync(OnRequestSucceeded, OnRequestFailed);
}
}
}
and my dataform:
<df:DataForm ItemsSource="{Binding}" Height="276" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataForm1" VerticalAlignment="Top" Width="376" EditEnded="dataForm1_EditEnded" AddingNewItem="dataForm1_AddingNewItem" DeletingItem="dataForm1_DeletingItem" CommandButtonsVisibility="All" />
Thanks for the help.
update: changed to this will answer in like 7 hours when it lets me
never mind I figured it out I changed my editended to this and deleted my addingNewitem method entirely. Now I just have to hide the ID field and it will be working perfectly
private void dataForm1_EditEnded(object sender, DataFormEditEndedEventArgs e)
{
if (e.EditAction == DataFormEditAction.Commit)
{
customerList = context.Web.Lists.GetByTitle("testlist");
SPCustomers printer = dataForm1.CurrentItem as SPCustomers;
ListItem items;
if (printer.id != 0)
{
items = customerList.GetItemById(printer.id);
}
else
{
ListItemCreationInformation itemcreationinfo = new ListItemCreationInformation();
items = customerList.AddItem(itemcreationinfo);
}
items["Title"] = printer.IPAddress;
items["make"] = printer.Make;
items["model"] = printer.Model;
items["x"] = printer.xCord;
items["y"] = printer.yCord;
items.Update();
context.ExecuteQueryAsync(OnRequestSucceeded, OnRequestFailed);
}
}