Remove items from DropDownList - c#

I have two DropDownLists one for the type of a soldier and one for the number of soldiers the player i allowed to buy. I populate ddlSoldiers with a LinqDataSource in the aspx page like this:
<asp:DropDownList ID="ddlSoldiers" runat="server"
DataSourceID="LinqDataSource2" DataTextField="type"
DataValueField="troopid" AutoPostBack="True">
</asp:DropDownList>
<asp:LinqDataSource ID="LinqDataSource2" runat="server"
ContextTypeName="BrowserSpill.LinqClass1DataContext" EntityTypeName=""
Select="new (type, troopid)" TableName="Troops">
</asp:LinqDataSource>
The other list ddlSoldierNumber is populated in the pageload like this:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userRole"] == null || Session["userRole"].Equals("admin"))
{
Response.Redirect("Login.aspx");
}
int userid = Convert.ToInt32(Session["userid"]);
if(string.IsNullOrEmpty(ddlSoldiers.SelectedValue))
{
var varTroopType = dc.Troops.Single(t => t.troopid == 1).type;
string troopType = Convert.ToString(varTroopType);
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for (int i = 1; i < numberOfBuildings + 1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
else
{
ddlSoldierNumber.Items.Clear();
string troopType = ddlSoldiers.SelectedItem.Text;
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for(int i = 1; i < numberOfBuildings+1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
}
But when i want to get the values from ddlSoldierNumber i only get the first value in that list. I try to get the number with the click of a button like this:
protected void btnBuySoldier_Click(object sender, EventArgs e)
{
string numbertobuy = ddlSoldierNumber.SelectedItem.Value;
lblAntall.Text = numbertobuy;
}
I have tried to put the line:
ddlSoldierNumber.Items.Clear();
other places but without any luck. Does anyone know how i can clear the number list after I press the button and before the ddlSoldierNumber get repopulated?

if you want to populate ddlSoldierNumber on the basis of selection from ddlSoldiers then you can not add values to ddlSoldierNumber in page load event. for that you have to add your page load event code in (ddlSoldiers) selected index change event.
protected void ddlSoldiers_SelectedIndexChanged(object sender, EventArgs e)
{
if (Session["userRole"] == null || Session["userRole"].Equals("admin"))
{
Response.Redirect("Login.aspx");
}
int userid = Convert.ToInt32(Session["userid"]);
if (string.IsNullOrEmpty(ddlSoldiers.SelectedValue))
{
var varTroopType = dc.Troops.Single(t => t.troopid == 1).type;
string troopType = Convert.ToString(varTroopType);
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for (int i = 1; i < numberOfBuildings + 1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
else
{
ddlSoldierNumber.Items.Clear();
string troopType = ddlSoldiers.SelectedItem.Text;
var varBuildingId = dc.Buildings.Single(b => b.soldierType == troopType).buildingid;
int buildingId = Convert.ToInt32(varBuildingId);
var varNumberOfBuildings =
dc.Towns.Single(t => (t.buildingid == buildingId) && (t.userid == userid)).number;
int numberOfBuildings = Convert.ToInt32(varNumberOfBuildings);
for (int i = 1; i < numberOfBuildings + 1; i++)
{
ddlSoldierNumber.Items.Add(i.ToString());
}
}
}

If I remember correctly, the pageload is run before your eventhandler for the button, have you tried placing the ddlSolderNumber.Items.Clear(); in the Click eventhandler after you change the label?
(I know this doesnt solve the issue with your first question)
For that you could try: (If Im confusing I apologize, Im bad at explaining myself)
You could create a "populate" method for your ddlSoldierNumber list, that you call after your click-event.
In your pageload, you could then on a check of "if (!PostBack)" run your default startup logic.

Related

I have SQLite db with 3 rows, when i delete data from row, data will lost but row will still, how can i delete that blank row?

I have xamarin app and I am using SQLite for saving data, if I have 3 rows and delete second row, then data will delete but row will be blank and its still here and problem is, that I need to load one column from every row. I am using for cycle and count to set maximum for it. But count says I have two rows so for cycle load just first and not second because second is on third line and second is blank.
I need to delete blank rows or to discover another solution how to load it. How can i delete blank DB?
Counting algorythm:
public int GetNumberPhotos()
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<Airplane>();
int count = 0;
if (db.Table<Airplane>().FirstOrDefault(l => l.Id == 1) != null)
count = db.Table<Airplane>().Count();
return count;
}
loading:
public int BetterUniReg()
{
int numberPhotos = GetNumberPhotos();
string[] allReg = new string[numberPhotos];
string[] uniReg = new string[numberPhotos];
int uniRegCnt = 0;
var db = new SQLiteConnection(_dbPath);
//db fill
for (int i = 0; i <= numberPhotos; i++)
{
if (db.Table<Airplane>().FirstOrDefault(b => b.Id == i) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(c => c.Id == i);
i--;
allReg[i] = rowData.Registration;
i++;
}
}
Here is delete code:
private async void deleteButton_Clicked(object sender, EventArgs e)
{
var action = await DisplayAlert("Delete", "Do you want delete picture?", "Cancel", "Delete");
if (action)
{
}
else
{
var butto = sender as Button;
var frame = butto.Parent.Parent.Parent.Parent as Frame;
await frame.FadeTo(0, 600);
var button = (Button)sender;
var plane = (Airplane)button.BindingContext;
var db = new SQLiteConnection(_dbPath);
db.Delete<Airplane>(plane.Id);
Refresh();
}
}
I have done walkaround by adding if its last row and its null then do one more cycle.
Here is code:
for (int i = 1; i <= numberPhotos; i++)
{
if (db.Table<Airplane>().FirstOrDefault(c => c.Id == i) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(c => c.Id == i);
allReg[regnumber] = rowData.Registration;
regnumber++;
}
if (db.Table<Airplane>().FirstOrDefault(c => c.Id == i) == null && i == numberPhotos)
{
numberPhotos = numberPhotos + 1;
}
}

ListView No Item Added

private void ItemGet()
{
for (int i = 0; i < this.listview2.VirtualListSize; i++)
{
var address = this.listview2.Items[i].Text;
int item_aid = this.lib.ReadInt32((IntPtr)(long.Parse(address, NumberStyles.HexNumber) + ItemData.oFFSET_AID));
int item_id = this.lib.ReadInt32((IntPtr)(Convert.ToInt32(address, 16) + ItemData.oFFSET_ID));
int item_type = this.lib.ReadInt32((IntPtr)(Convert.ToInt32(address, 16) + ItemData.oFFSET_TYPE));
if ((item_aid.ToString().Length == 6) && (item_aid > 110000 && item_aid < 200000)
&& item_id.ToString().Length == 3 - 6)
{
this._itemslist.Add(new ItemResults(item_aid, item_aid, item_type));
this.ItemDetailsListView.Items.Add(new ListViewItem(new string[] {
item_aid.ToString(),
item_id.ToString(),
item_type.ToString()}));
MessageBox.Show(item_aid.ToString());
}
}
}
when i put messagebox show the messaage box is not pop i use cheat engine library to scan value and put it on listview I have no idea why it's not working
private void ScanTimer_Tick(object sender, EventArgs e)
{
this.ScanTimer.Enabled = false;
this.lib.iResetValues();
this.listview1.Refresh();
this.listview2.Refresh();
if (this.started)
{
var t = Task.Factory.StartNew(() => GetMonster()).ContinueWith((itemgetTask) => ItemGet()).ContinueWith((attackTask) => Attacks()).ContinueWith((teleportTask) => Teleport()).ContinueWith((pickuptTask) => Pickup());
Task.WaitAll(t);
this.lib.iNewScan();
MonsterScannerTimer.Start();
ItemScannerTimer.Start();
}
}
i call it here.
First time answering a question, I hope I can help.
Maybe you would be better off with storing the data you would normally add directly to your list into a ObservableCollection.
Here is a link to the class: https://learn.microsoft.com/de-de/dotnet/api/system.collections.objectmodel.observablecollection-1?view=netframework-4.7.2
There are plenty of ways to add it to your listview.

How to Load all the Objects in an Array List

I am trying to figure out how to load through an Array List of Objects. I am able to retrieve the last Object in the Array, but it will not let me Load any other Object after that. here is part of the code I have. As you can see it saves the object to the List, but when I click the loadLastBtn it will only load the most recent entry and if I hit it again after that nothing loads.
List<Members> lstMembers = new List<Members>();
private int hold;
private void submitBtn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(firstNameTxt.Text) || string.IsNullOrEmpty(lastNameTxt.Text)
|| string.IsNullOrEmpty(userNameTxt.Text) ||
string.IsNullOrEmpty(passwordTxt.Text) || string.IsNullOrEmpty(confPassTxt.Text)
|| string.IsNullOrEmpty(majorBox.Text) || string.IsNullOrEmpty(specialtyBox.Text))
{
MessageBox.Show("You must enter in all fields before moving forward");
}
else
{
Members m1 = new Members(firstNameTxt.Text, lastNameTxt.Text, userNameTxt.Text,
passwordTxt.Text, confPassTxt.Text, majorBox.Text,
specialtyBox.Text);
lstMembers.Add(m1);
}
}
private void loadLastBtn_Click(object sender, EventArgs e)
{
firstNameTxt.Text = lstMembers[hold].FirstName;
lastNameTxt.Text = lstMembers[hold].LastName;
userNameTxt.Text = lstMembers[hold].UserName;
passwordTxt.Text = lstMembers[hold].Password;
confPassTxt.Text = lstMembers[hold].ConfPassword;
majorBox.Text = lstMembers[hold].Major;
specialtyBox.Text = lstMembers[hold].Specialty;
hold++;
}
I have edited my answer. this will now print each user one by one each time I hit loadLastBtn, but it does show them from the first user to the last, where I need it to shower the last user to the first.
What you need is something like this:
// -1 Indicates that you should start at the end of the list
int index = -1;
private void loadButton_Click(object sender, EventArgs e)
{
if (members != null && members.Count > 0) // Avoid accessing if list is empty or null
{
if (index == -1)
index = members.Count - 1;
firstNameTxt.Text = lstMembers[index].FirstName;
lastNameTxt.Text = lstMembers[index].LastName;
userNameTxt.Text = lstMembers[index].UserName;
passwordTxt.Text = lstMembers[index].Password;
confPassTxt.Text = lstMembers[index].ConfPassword;
majorBox.Text = lstMembers[index].Major;
specialtyBox.Text = lstMembers[index].Specialty;
if (index == 0) // Reached beginning of array
index = -1; // Indicate that next time the last element must be accessed
else
--index;
}
}
private int hold = lstMembers.Count -1;
private void loadLastBtn_Click(object sender, EventArgs e)
{
firstNameTxt.Text = lstMembers[hold].FirstName;
lastNameTxt.Text = lstMembers[hold].LastName;
userNameTxt.Text = lstMembers[hold].UserName;
passwordTxt.Text = lstMembers[hold].Password;
confPassTxt.Text = lstMembers[hold].ConfPassword;
majorBox.Text = lstMembers[hold].Major;
specialtyBox.Text = lstMembers[hold].Specialty;
hold--;
}

How to get the textbox value in ascx page?

In my project I have 3 user controls, those are displayed in master page. When I entered the value in textbox it doesn't getting current value, it will display previous value.
Code:
1st Data Bound:
protected void dlFirstZone_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)) && (e.Item.DataItem != null))
{
using (GroceriesServiceClient groceriesServiceClient = new GroceriesServiceClient())
{
HomeMaster pp = (HomeMaster)e.Item.DataItem;
int prdItem = pp.ProductId;
ShoppingCart shopingCartParameter = new ShoppingCart();
//if (pp.DisplayOrder == 1)
//{
Products products = new Products();
if (basePage.BasePageWebSession != null)
{
shopingCartParameter.UserId = Convert.ToInt32(basePage.BasePageWebSession.UserId);
cartlist = groceriesServiceClient.ShoppingCart_UserProductsList(shopingCartParameter);
var td = (from c in cartlist
where c.ProductId == prdItem
select c);
if (td.ToList().Count > 0)
{
TextBox txtQtyDataview = (TextBox)e.Item.FindControl("txtQty");
txtQtyDataview.Text = td.First().Quantity.ToString();
}
}
//}
//else
}
}
}
2nd ItemCommand event handler:
protected void dlProduct_ItemCommand(object source, DataListCommandEventArgs e)
{
HomeMaster q = (HomeMaster)e.Item.DataItem;
if (e.CommandName == "AddToCart")
{
using (GroceriesServiceClient gsc = new GroceriesServiceClient())
{
ShoppingCart shoppingcart = new ShoppingCart();
shoppingcart.UserId = basePage.BasePageWebSession.UserId;
shoppingcart.UserName = basePage.BasePageWebSession.UserName;
shoppingcart.ProductId = Convert.ToInt32(Convert.ToInt32(dlProductDataView.DataKeys[e.Item.ItemIndex]));
TextBox tb1 = (TextBox)e.Item.FindControl("txtQty");
if (!string.IsNullOrEmpty(tb1.Text))
shoppingcart.Quantity = Convert.ToInt32(tb1.Text);
else
shoppingcart.Quantity = 1;
shoppingcart = gsc.ShoppingCart_InsertOrUpdate(shoppingcart);
Response.Redirect(Request.RawUrl);
}
}
}
You can use findControl to find the textbox within a user control, like this (assuming you have a textbox called tb1 in a userconrol called uc1:
me.uc1.findControl("tb1").text
The better way, though, is to expose a public function that can be called to return the value:
In UserControl, create a public function:
public function getValue() as string
return me.tb1.text
end Function
Then you can access it from any page or control that has a reference to the user control:
dim whatsMyName as string = me.uc1.getValue()

Searching a DataGridView for a match or partial match

Tried to sift through the google results; no luck. What I'm trying to do is, given some text in a TextBox: search for at least a partial match in any column of my DataGridView, and have the control select the first row (show it as the top row and have it highlighted) that it encounters with that partial match.
Here is my declaration of the DataSource for the DataGridView and how the columns are organized:
var queryData = from va in xdoc.Descendants("language")
select new
{
StringID = va.Parent.Parent.Attribute("id").Value,
Language = va.Attribute("name").Value,
LanguageData = va.Element("value").Value,
};
var organizedData = from x in queryData
group x by x.StringID into xg
select new
{
StringID = xg.Key,
English = xg.SingleOrDefault(x => x.Language == "ENGLISH_US").LanguageData,
Custom = xg.SingleOrDefault(x => x.Language == languageBox.SelectedItem.ToString()).LanguageData,
};
mainView.DataSource = organizedData.ToList();
And here is the current definition of the function that handles a click of the 'Search' button:
private void searchButton_Click(object sender, EventArgs e)
{
int currentIndex = mainView.CurrentRow.Index;
if (searchBox.Text.Length == 0)
{
mainView.CurrentCell = mainView[0,0];
mainView.Focus();
return;
}
}
Something like this might get you close:
string searchForText = "whatever";
DataGridViewRow rowFound = mainView.Rows.OfType<DataGridViewRow>()
.FirstOrDefault(row => row.Cells.OfType<DataGridViewCell>()
.Any(cell => ((dynamic)cell.Value).StringID.Contains(searchForText)));
if (rowFound != null) {
mainView.Rows[rowFound.Index].Selected = true;
mainView.FirstDisplayedScrollingRowIndex = rowFound.Index;
}

Categories