I have 2 GridViews with select rows enabled in my form. Can someone help me on coding where it can redirect to a different form on a click of a select in GridView instead of a button click (like I have coded)?
namespace TicketsApp
{
public partial class SearchTickets : System.Web.UI.Page
{
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["TicketsConnectionString"].ConnectionString;
ArrayList selectedSportEvent = new ArrayList();
protected void btnSearch_Click1(object sender, EventArgs e)
{
DataAccess myData = new DataAccess();
ArrayList parameters = new ArrayList();
//Updates the selected by the dates specified
SqlDataReader results;
parameters.Add(new SqlParameter("#StartDate", CalStartDate.SelectedDate));
parameters.Add(new SqlParameter("#EndDate", CalEndDate.SelectedDate));
results = myData.GetDataReader("SearchTickets", connect, parameters);
//Clear sort expression
grdSearch.DataSourceID = String.Empty;
this.grdSearch.DataSource = results;
this.grdSearch.DataBind();
//makes gridview Search visible
grdSearch.Visible = true;
grdUpdated.Visible = false;
//make sure the dates are selected
if (CalStartDate.SelectedDate < DateTime.Today || CalEndDate.SelectedDate < DateTime.Today)
{
CalStartDate.Focus();
return;
}
if (CalEndDate.SelectedDate < DateTime.Today)
{
lblCalError.Visible = true;
return;
}
}
protected void btnUpdate_Click1(object sender, EventArgs e)
{
DataAccess myData = new DataAccess();
ArrayList parameters = new ArrayList();
//updates the selection by the sport selected
SqlDataReader results;
parameters.Add(new SqlParameter("#SportName", ddlSportType.SelectedItem.ToString()));
results = myData.GetDataReader("SearchTicketsBySport", connect, parameters);
//Clear sort expression
grdUpdated.DataSourceID = String.Empty;
this.grdUpdated.DataSource = results;
this.grdUpdated.DataBind();
//Makes gridview updated visible
grdUpdated.Visible = true;
grdSearch.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session.Remove("EventData");
}
CalStartDate.SelectedDate = DateTime.Today;
CalEndDate.SelectedDate = DateTime.Today;
}
//Adds the item selected to the array
protected void grdSearch_SelectedIndexChanged(object sender, EventArgs e)
{
selectedSportEvent.Clear();
int x;
for (x = 1; x < grdSearch.SelectedRow.Cells.Count; x++)
{
int selectedRow = grdSearch.SelectedIndex;
GridViewRow r = grdSearch.Rows[selectedRow];
Session["EventID"] = r.Cells[1].Text;
Session["description"] = r.Cells[2].Text;
Session["ticketcost"] = r.Cells[7].Text;
Session["numtickets"] = r.Cells[6].Text;
Session["State"] = r.Cells[9].Text;
Session["Section"] = r.Cells[4].Text;
Session["Row"] = r.Cells[5].Text;
Session["date"] = r.Cells[8].Text;
}
}
//Adds the item selected to the array
protected void grdUpdated_SelectedIndexChanged(object sender, EventArgs e)
{
selectedSportEvent.Clear();
int x;
for (x = 1; x < grdUpdated.SelectedRow.Cells.Count; x++)
{
int selectedRow = grdUpdated.SelectedIndex;
GridViewRow r = grdUpdated.Rows[selectedRow];
Session["EventID"] = r.Cells[1].Text;
Session["description"] = r.Cells[2].Text;
Session["ticketcost"] = r.Cells[7].Text;
Session["numtickets"] = r.Cells[6].Text;
Session["State"] = r.Cells[9].Text;
Session["Section"] = r.Cells[4].Text;
Session["Row"] = r.Cells[5].Text;
Session["date"] = r.Cells[8].Text;
}
}
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
//Redirects to TicketOrder form
Response.Redirect("TicketOrder.aspx");
}
protected void CalStartDate_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date < (System.DateTime.Now.AddDays(-1)))
{
e.Day.IsSelectable = false; e.Cell.Font.Strikeout = true;
}
}
}
}
Related
Hello I'm trying to click a button to remove and item but I keep getting an
'IndexOutOfRange' Exception.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
clientNum = clientList.Items.Count;
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
if (dateSeletion[clientList.SelectedIndex] != null)
{
dateCalender.SelectionStart = todayDate[clientList.SelectedIndex];
Check();
}
else
{
nameLbl.Text = nameSeletion[clientList.SelectedIndex];
dateText.Text = "";
}
}
The if (dateSeletion[clientList.SelectedIndex] != null) is where I'm having the error.
The button code is
private void button1_Click(object sender, EventArgs e)
{
clientList.Items.Remove(clientList.Items[clientList.SelectedIndex]);
}
the dateSelection is defined in the save button and Initialization
private void SaveBtn_Click(object sender, EventArgs e)
{
//save the list array for names
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
dateSeletion[clientList.SelectedIndex] = dateCalender.SelectionStart.Date.ToShortDateString() +
" " + clientTime.Value.ToShortTimeString();
todayDate[clientList.SelectedIndex] = dateCalender.SelectionStart;
dateCalender.BoldedDates = todayDate;
Check();
}
public ClientForm()
{
InitializeComponent();
clientNum = clientList.Items.Count;
todayDate = new DateTime[clientNum];
dateSeletion = new string[clientNum];
nameSeletion = new string[clientNum];
clientTime.CustomFormat = "hh:mm tt";
//initialize the list array for names
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
}
Try this
clientList.RemoveAt(clientList.SelectedIndex);
I'm sorry that the title is confusing but I did not know how to ask this question; if someone can help with a better title I would appreciate it.
I am building a database of players and their match performance. The matches are displayed using a tab control, inside the matches are fields that are stored in a panel. The amount of matches goes up to 5, therefore each field is an array of size 5 to represent different values for different matches. I have ran into the problem of trying to save the amount of tabs (matches) there are for that unique player.
Because the amount of tabs carries over to the next player shown, I tried to iterate through all the matches and all the fields for that player, determine which matches contain empty fields and respectively delete that tab (match). So if player 1 has 3 matches with values in fields, but player 2 only has 2 matches that contain values in fields, the 3rd match (tab) will be deleted as the fields have no values.
to better explain, this is the GUI:
Picture
My attempt at iterating through the field of each match looks like this:
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
i++;
}
However I am presented with the error: Cannot implicitly convert type 'int' to 'int[]'
I would really appriciate if someone could help me out here, I understand that the code is long but It is organised and titled so that should help.
Full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================DATA STRUCTURE ===========================
[Serializable]
private struct Player
{ //CONSTRUCTOR
public Player(int noOfMatches)
{
uniquePlayerId = new int[noOfMatches];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
matchesCount = 0;
csNumber = new int[noOfMatches];
killsNumber = new int[noOfMatches];
deathsNumber = new int[noOfMatches];
assistsNumber = new int[noOfMatches];
minutesNumber = new int[noOfMatches];
for (int i = 0; i < noOfMatches; ++i)
{
uniquePlayerId[i] = 0;
csNumber[i] = 0;
killsNumber[i] = 0;
deathsNumber[i] = 0;
assistsNumber[i] = 0;
minutesNumber[i] = 0;
}
}
//DATA TYPES
public int[] uniquePlayerId;
public int[] csNumber;
public int[] killsNumber;
public int[] deathsNumber;
public int[] assistsNumber;
public int[] minutesNumber;
public int matchesCount;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
//GLOBAL VARIABLES
public ArrayList GameDB;
public ArrayList playerMatch;
private int currentEntryShown = 0;
private int numberOfEntries = 0;
private string filename = "W:\\test.dat";
public string prevImage = "";
// =========================================================================
// ====================== STARTING POINT ===================================
// =========================================================================
public Form1()
{
InitializeComponent();
GameDB = new ArrayList();
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown < GameDB.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries;
currentEntryShown = numberOfEntries - 1;
Player aNewStruct = new Player(5);
GameDB.Add(aNewStruct);
ShowData();
addNewPlayerBtn.Enabled = true;
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData();
addNewPlayerBtn.Enabled = true;
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
numberOfEntries--;
GameDB.RemoveAt(currentEntryShown);
SaveData();
currentEntryShown--;
if (currentEntryShown <= GameDB.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.Title = "Select an image file";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.imagePath = openFileDialog1.FileName;
GameDB[currentEntryShown] = aNewStruct;
playerPictureBox.ImageLocation = openFileDialog1.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void searchBtn_Click(object sender, EventArgs e)
{
string toFind;
string source;
toFind = searchInput.Text;
toFind = toFind.ToLower();
for (int i = 0; i < GameDB.Count; ++i)
{
source = ((Player)GameDB[i]).playerIgName + ((Player)GameDB[i]).contactStreet;
source = source.ToLower();
if (source.Contains(toFind))
{
currentEntryShown = i;
ShowData();
UpdatePrevNextBtnStatus();
break;
}
if (i == (GameDB.Count - 1))
{
MessageBox.Show(toFind + " not found");
}
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void addNewMatchBtn_Click(object sender, EventArgs e)
{
TabPage newTP = new TabPage();
if (tabMatches.TabCount <= 4)
{
tabMatches.TabPages.Add(newTP);
int TabPageNumber = tabMatches.SelectedIndex + 1;
tabMatches.TabPages[TabPageNumber].Text = "Match " + (TabPageNumber + 1);
tabMatches.SelectTab(TabPageNumber);
deleteMatchBtn.Enabled = true;
panel1.Parent = tabMatches.SelectedTab;
}
ShowData();
}
private void deleteMatchBtn_Click(object sender, EventArgs e)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
int lastTabNumber = tabMatches.TabCount - 1;
tabMatches.SelectTab(lastTabNumber);
if (tabMatches.SelectedIndex < 1) deleteMatchBtn.Enabled = false;
}
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
GameDB[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
//Match data
private void tabMatches_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Parent = tabMatches.SelectedTab;
ShowData();
}
private void numCS_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.csNumber[tabMatches.SelectedIndex] = (int)numCS.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numKills_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.killsNumber[tabMatches.SelectedIndex] = (int)numKills.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numDeaths_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.deathsNumber[tabMatches.SelectedIndex] = (int)numDeaths.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numAssists_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.assistsNumber[tabMatches.SelectedIndex] = (int)numAssists.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numMinutes_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.minutesNumber[tabMatches.SelectedIndex] = (int)numMinutes.Value;
GameDB[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((Player)GameDB[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((Player)GameDB[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactTelephone;
playerPictureBox.ImageLocation = ((Player)GameDB[currentEntryShown]).imagePath;
numCS.Value = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
numKills.Value = ((Player)GameDB[currentEntryShown]).killsNumber[tabMatches.SelectedIndex];
numDeaths.Value = ((Player)GameDB[currentEntryShown]).deathsNumber[tabMatches.SelectedIndex];
numAssists.Value = ((Player)GameDB[currentEntryShown]).assistsNumber[tabMatches.SelectedIndex];
numMinutes.Value = ((Player)GameDB[currentEntryShown]).killsNumber[tabMatches.SelectedIndex];
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, GameDB);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
GameDB = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = GameDB.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close();
Environment.Exit(1);
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
Player aNewStruct = new Player(5);
GameDB.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
GameDB.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Player)x).playerIgName.CompareTo(((Player)y).playerIgName);
}
}
// =========================================================================
// ====================== MISC STUFF =======================================
// =========================================================================
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void developerToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("By Szymon Zmudzki: 13042432");
}
}
}
Try change this
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
To use the csNumber which is int[] in the for loop
int i = 0;
while (i < 5)
{
if (((Player)GameDB[currentEntryShown]).csNumber[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
To find out the value of tabMatches.TabCount, add this line when you run the program and see it in the output window: (To answer your question, I would assume the TabCount start with 1. That's the default value of any .Count() call to an array of integer. But this is the best way to know for sure.)
System.Diagnostics.Debug.WriteLine(tabMatches.TabCount);
How can I select each row in the grid(gridCustomer) and the second grid(gridOrder) displays object information in my order?
I'll choose the first row of the grid(gridCustomer) but the grid (gridOrder) will not display anything.
Project File
Video
private void gridCustomer_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//var s = gridCustomer.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.gridCustomer.Rows[e.RowIndex];
var selectedItme = row.Cells["Id"].Value;
var objOrder = orderBusiness.OrderFindById(Convert.ToInt32(selectedItme));
gridOrder.DataSource = objOrder;
}
}
private void gridCustomer_CellClick(object sender, DataGridViewCellEventArgs e)
{
if(e.RowIndex >= 0)
{
DataGridViewRow row = this.gridCustomer.Rows[e.RowIndex];
var selectedItme = row.Cells["Id"].Value;
var objOrder = orderBusiness.OrderFindById(Convert.ToInt32(selectedItme));
/* Add This */
BindingList<Order> bl = new BindingList<Order> { objOrder };
gridOrder.DataSource = bl;
}
}
I have a form with databound combobox, with dropstyle set as dropdown, so users could type in the combobox.
My problem is that when users type in the combobox and the value typed matches one of the values bound to the combobox it won't change the selectedindex, even though I've tried too. Instead, it sets the selected index to -1 (and thus the selected value is null).
Can anyone help? here's my code (one of my tries, i tried other approaches but none helped).
private void setCombo()
{
comboFromOther.DisplayMember = "tbl10_KupaID";
comboFromOther.ValueMember = "tbl10_KupaID";
comboFromOther.DataSource = dsKupotGemel.Tables[0];
}
private void comboToOther_TextChanged(object sender, EventArgs e)
{
comboDetail = changedComboText(2, comboToOther.Text);
textToOther.Text = comboDetail[0];
if (comboDetail[0] == "")
{
}
else
{
comboToOther.SelectedIndex = System.Int32.Parse(comboDetail[1]);
comboToOther.SelectedValue = System.Int32.Parse(comboDetail[2]);
}
}
private string[] changedComboText(int iComboType, string comboString)
{
if (groupCalculate.Visible == true)
{
groupCalculate.Visible = false;
}
string[] kupaDetail = new string[3];
kupaDetail[0] = "";
kupaDetail[1] = "";
kupaDetail[2] = "";
for (int i = 0; i <= dsKupotGemel.Tables[0].Rows.Count - 1; i++)
{
if (comboString == dsKupotGemel.Tables[0].Rows[i][0].ToString())
{
kupaDetail[0] = dsKupotGemel.Tables[0].Rows[i][1].ToString();
kupaDetail[1] = i.ToString();
kupaDetail[2] = comboString;
break;
}
else
{
}
}
return kupaDetail;
}
Maybe there is an error in your code?
Here is a working sample:
// Fields
private const string NameColumn = "Name";
private const string IdColumn = "ID";
private DataTable table;
Next, initialization
// Data source
table = new DataTable("SomeTable");
table.Columns.Add(NameColumn, typeof(string));
table.Columns.Add(IdColumn, typeof(int));
table.Rows.Add("First", 1);
table.Rows.Add("Second", 2);
table.Rows.Add("Third", 3);
table.Rows.Add("Last", 4);
// Combo box:
this.comboBox1.DisplayMember = NameColumn;
this.comboBox1.ValueMember = IdColumn;
this.comboBox1.DataSource = table;
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
this.comboBox1.TextChanged += comboBox1_TextChanged;
this.comboBox1.SelectedIndexChanged += this.comboBox1_SelectedIndexChanged;
Event handlers - TextChanged:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < table.Rows.Count; i++)
{
if (table.Rows[i][NameColumn].ToString() == this.comboBox1.Text)
{
this.comboBox1.SelectedValue = table.Rows[i][IdColumn];
break;
}
}
}
Event handlers - SelectedIndexChanged:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Do here what is required
}
With this code, as soon as user types full name of item into combo box, SelectedIndexChanged is invoked through TextChanged.
There is also such thing as AutoCompleteMode, AutoCompleteSource. Don't know where they fit into your application.
I want to do a simple poll page and I have a code that should work but it seems that the .cs file don't want to recognize the gridview
public partial class _Default : System.Web.UI.Page
{
int Count = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnVote_Click(object sender, EventArgs e)
{
if (radVote.SelectedItem != null)
{
InsertVotes(radVote.SelectedItem.ToString());
}
else
{
lblStatus.ForeColor = Color.Red;
lblStatus.Text = "Please select at least one option to vote for poll";
}
}
protected void InsertVotes(string theVote)
{
try
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("Votes.xml"));
XmlElement parentelement = xmldoc.CreateElement("Vote");
XmlElement votechoice = xmldoc.CreateElement("Choice");
votechoice.InnerText = theVote;
parentelement.AppendChild(votechoice);
xmldoc.DocumentElement.AppendChild(parentelement);
xmldoc.Save(Server.MapPath("Votes.xml"));
lblStatus.ForeColor = Color.Green;
lblStatus.Text = "Thank you for your vote.";
}
catch
{
lblStatus.Text = "Sorry, unable to process request. Please try again.";
}
}
protected void readXML()
{
int mCount = 0;
int iCount = 0;
int gCount = 0;
XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("Votes.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count > 0)
{
int dscount = ds.Tables[0].Rows.Count;
for (int i = 0; i < dscount; i++)
{
if (ds.Tables[0].Rows[i][0].ToString() == "Mozilla")
mCount++;
else if (ds.Tables[0].Rows[i][0].ToString() == "Internet Explorer")
iCount++;
else if (ds.Tables[0].Rows[i][0].ToString() == "Google Chrome")
gCount++;
}
double theTotal;
theTotal = mCount + iCount + gCount;
double mPercent;
double oPercent;
double gPercent;
mPercent = (mCount / theTotal) * 100;
oPercent = (iCount / theTotal) * 100;
gPercent = (gCount / theTotal) * 100;
double totalpercentage = mPercent + oPercent + gPercent;
string[] votescount = { mCount.ToString(), iCount.ToString(), gCount.ToString() };
string[] array = { mPercent.ToString(), oPercent.ToString(), gPercent.ToString() };
DataTable dt = new DataTable();
dt.Columns.Add("OPTION_NAME");
dt.Columns.Add("VOTES");
dt.Columns.Add("PERCENTAGE");
int count = radVote.Items.Count;
Count = count + 1;
for (int i = 0; i < count; i++)
{
dt.Rows.Add();
dt.Rows[i]["OPTION_NAME"] = radVote.Items[i].ToString();
dt.Rows[i]["VOTES"] = votescount[i];
dt.Rows[i]["PERCENTAGE"] = array[i];
}
dt.Rows.Add("Total", theTotal, totalpercentage);
gvResult.DataSource = dt;
gvResult.DataBind();
}
else
{
gvResult.DataSource = null;
gvResult.DataBind();
}
}
protected void butResults_Click(object sender, EventArgs e)
{
readXML();
}
int cnt = 0;
protected void gvResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
cnt++;
Label lblpercent = (Label)e.Row.FindControl("lblpercentage");
HtmlTable tblpercent = (HtmlTable)e.Row.FindControl("tblBar");
tblpercent.Width = lblpercent.Text+"%";
if (lblpercent.Text == "0")
{
tblpercent.Visible = false;
}
if (cnt == Count)
{
e.Row.CssClass = "TablePollResultFoot";
}
foreach (TableCell tc in e.Row.Cells)
{
tc.Attributes["style"] = "border-color:#CCCCCC";
}
}
protected void btnResult_Click(object sender, EventArgs e)
{
readXML();
}
}
the gvResult, radVote, lblStatus all have an error saying that the name doesn't exist in the current context. I have checked the names and everything seems to be fine but still I get this errors.
In the html I have radiobuttonlist, a gridview, one button for voting and one button for showing the results
Your page files may have fallen out of synch with the designer file. Create a new page, move your grid there, and see if that fixes it?
You could manually add declaration of control in the designer file yourself, but this is not recommended.
Or, you can just delete the designer file and have ASP.Net regenerate it. There's a longer explanation here but basically, you just delete the problem .designer.cs file. To regenerate it, click on the .aspx file in Solution Explorer, then click “Convert to Web Application”.