What's wrong in this code? Code works, but it returns empty gridview?
If I debug code, I can see that my string plName contains players name, however when I add it to object it's empty? Also, how I can check if my query result is null? I believe this is not best way to do it...
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
List<AllPlayers> listOfPlayers = new List<AllPlayers>();
string plName = "";
string plStatus = "";
using (PlayerEntities playerEntities = new PlayerEntities())
{
var query = (from pl in playerEntities.players from st in playerEntities.player_status.Where(a => a.players_key == pl.players_key).DefaultIfEmpty()
from pt in playerEntities.play_times.Where(b => b.players_key == pl.players_key).DefaultIfEmpty() select new { pl, st, pt }).ToList();
foreach (var item in query)
{
plName = item.pl.player_name.ToString();
try // better way check if this is NULL ?
{
plName = item.st.default_times_start.ToString();
}
catch(Exception ex)
{
ex.Message.ToString();
}
AllPlayers demo = new AllPlayers(plName, plStatus);
listOfPlayers.Add(demo);
}
}
GridView1.DataSource = listOfPlayers;
GridView1.DataBind();
}
}
ASPX:
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
Related
I have a dropdownlist in a usercontrol as shown below
<asp:dropdownlist id="ddlLanguage" runat="server" AutoPostBack="true" EnableViewState="true" onselectedindexchanged="ddlLanguage_SelectedIndexChanged">
</asp:dropdownlist>
my selectedchanged event is not getting fired even once
in code behind
if (!IsPostBack)
{
//dt - is list of languages availbale in DB
//value[0]-contains lang currently to be binded to dropdownlist based
//remaining values (values [1]) to are to be populated to textbox
LoadModuleInfo(dt,values)
}
private void LoadModuleInfo(System.Data.DataTable dtLanguages, string[] values)
{
this.txbxModuleName.Text = values[1];
this.ddlLanguage.DataSource = dtLanguages;
this.ddlLanguage.DataTextField = "language_description";
this.ddlLanguage.DataValueField = "language";
this.ddlLanguage.DataBind();
// set up selections on the screen
this.ddlLanguage.SelectedIndex = this.getIndex(dtLanguages, values[0]);
}
protected void ddlLanguage_SelectedIndexChanged(object sender, System.EventArgs e)
{
//get new values ( values[0] and values[1])
LoadModuleInfo(dtLanguages, values);
}
protected int getIndex(DataTable dt, string recordId)
{
int intCt = 0;
foreach (System.Data.DataRow dr in dt.Rows)
{
if (dr[0].ToString() == recordId)
{
break;
}
else
{
intCt++;
}
}
return intCt;
}
i have wriiten the above code, but selectedchanged event is not fired for dropdownlist control available in USERCONTROL.
Please help.
If you page not refreshed at all .. most probably you have a javascript error in the page
Kindly remove below line from your code and try
this.ddlLanguage.DataValueField = "language";
or
change this too language to language_description
I am using a wizard. and in step two the user can add information about a location that will be stored. He can add as many locations as he likes.
In step three I want to enter more information about the specific location.
To select which location to use I have ASP:dropdownlist that I populate when user enters stuff.
I want to change index but it just does not work It never goes into the function when I tried debugging. I am using a label to debug.
When I change the selected item the page reloads and the first item in the dropdown list is always selected even though I selected something else. I do not understand why that happens
here is what I have
ASPX File
Select location to enter data for:
<asp:DropDownList ID="s3_location_list" runat="server" AutoPostBack="true" OnSelectedIndexChanged="stepThree_location_list_SelectedIndexChanged">
</asp:DropDownList>
Current location index:
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
CS files
/*This is where I add data to the drop down list
protected void stepTwo_addLocationData(object Sender, System.EventArgs e)
{
//initialize a temporary string array to get all the data from the form
//Console.Write("AAAAA"+ Context.Items["IsRefreshed"]);
Boolean refreshed = (Boolean)Context.Items["IsRefreshed"];
if (!refreshed)
{
//if user is adding a new entry to the location table
LocationData new_location = new LocationData();
//add stuff to locationData
if (stepTwo_locationTableIndex == -1)
{
//add the new_location element into the location_data array
location_data.Add(new_location);
//redraw the table
DataRow dr = dt.NewRow();
dr["Location"] = new_location.City;
//dr["Name"] = loc;
dt.Rows.Add(dr);
}
else
{
location_data[stepTwo_locationTableIndex] = new_location;
dt.Rows[stepTwo_locationTableIndex]["Location"] = City.Text;
}
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
///CreateTable();
stepFive_setLocationListOptions();
stepThree_setLocationListOptions();
stepTwo_resetForm();
}
/*this is the page load on step 3
protected void stepThree_load()
{
if (!IsPostBack && Session["s_s3_locationDropdownIndex"] == null)
{
stepThree_locationDropdownIndex = s3_location_list.SelectedIndex;
Session["s_s3_locationDropdownIndex"] = stepThree_locationDropdownIndex;
}
else
{
stepThree_locationDropdownIndex = (int) Session["s_s3_locationDropdownIndex"];
}
s3_location_list.SelectedIndex = stepThree_locationDropdownIndex;
Label3.Text = "" + s3_location_list.SelectedIndex;
}
/*this is my where I populate the list
protected void stepThree_setLocationListOptions()
{
s3_location_list.Items.Clear();
int i = 0;
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
/* this is the function thats callled when selected index is changed.
protected void stepThree_location_list_SelectedIndexChanged(object sender, EventArgs e)
{
Label3.Text = "Hello";
}
I think the problem is the order of execution. You should only initialize a DropDownList once, otherwise it will overwrite your SelectedIndex. For example, use the OnInit event:
<asp:DropDownList ID="s3_location_list"
runat="server"
OnInit="s3_location_list_Init"/>
And write the event method like this:
protected void s3_location_list_Init(object sender, EventArgs e)
if (!IsPostBack) {
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
}
I am wanting to know if there is a way to populate a list box with both text and value. The text bit is easy, but I want a value so I can have a user select something in it then press a button which gets the chosen value and uses an SQL query to do the rest.
My code so far for populating the text is:
listAllLessons.Items.Add(detail);
It runs in a loop and is populated from a database.
Thanks
You can do this in Web Forms:
HTML Side:
<asp:DropDownList ID="ddlList"
runat="server" />
<br />
<asp:Button ID="btnSubmit"
runat="server"
OnClick="btnSubmit_Click"
Text="Click Me" />
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Generate 20 items
foreach(var count in Enumerable.Range(1, 20))
{
var newItem = new ListItem();
newItem.Value = count.ToString();
newItem.Text = "Item " + count.ToString();
ddlList.Items.Add(newItem);
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Gets the selected value
var selectedValue = ddlList.SelectedValue;
System.Diagnostics.Debugger.Break();
}
Have you tried concatenating the items just like this:
while (reader.Read())
{
ListBox1.Items.Add(reader[0].ToString() + "\t" + reader[1].ToString());
}
Please try this:
while (reader.Read())
{
ListItem li = new ListItem(Convert.ToString(reader["test"]), Convert.ToString(reader["value"]));
ListBox1.Items.Add(li);
}
This worked for me.
dt = db.GetAllEmployeeForManagement();
foreach (DataRow item in dt.Rows)
{
ListItem li = new ListItem(Convert.ToString(item["Name"]), Convert.ToString(item["EmployeeID"]));
if (!ListBox1.Items.Equals(li.Text))
{
ListBox1.Items.Add(li);
}
}
where dt is actually a ref name of Datasource so.. it is quite simple!
I am populating an html table from a datatable with an edit button in each table row for each datatable row.
I am adding the edit button in code as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (UserName != null && UserName != "")
{
hUserName.Value = UserName;
}
else
if (hUserName.Value != "")
UserName = hUserName.Value;
ShowTrainingEntry();
ShowUserTraining(); <-------------- this method populates table
hTID.Value = TrainingID.ToString();
}
}
public void ShowUserTraining()
{
....
dTotalTrainingHours += ShowTrainingInPeriod(dv);
....
}
protected decimal ShowTrainingInPeriod(DataView dv)
{
....
foreach (DataRowView rowView in dv)
{
....
Button bEdit = new Button();
int iTID = Convert.ToInt32(dr["ID"].ToString());
bEdit.Text = "Edit";
bEdit.ID = "btnEdit_" + iTID.ToString();
bEdit.CommandName = "Edit";
bEdit.CommandArgument = iTID.ToString();
bEdit.Command += new CommandEventHandler(btnEdit_Click);
....
}
....
}
public void btnEdit_Click(object sender, CommandEventArgs e)
{
clsLog.WriteLog("btnEdit_Click fired.");
clsLog.WriteLog("\t" + e.CommandName);
clsLog.WriteLog("\t" + e.CommandArgument.ToString());
UserName = hUserName.Value;
TrainingID = Convert.ToInt32(e.CommandArgument);
ShowTrainingEntry();
ShowUserTraining();
}
as requested - HTML table:
<asp:Table ID="tblMain" runat="server" Width="900" CellPadding="3" CellSpacing="0" CssClass="noborder">
</asp:Table>
btnEdit_Click is NOT being fired (no log entries).
I have researched this for several hours and the only thing consistent I have found is that the event must be wired to the button during Page_Load which I believe is happening correctly.
Any help would be greatly appreciated.
Thanks,
John
try to do event register
btnEdit_Click.Click += new EventHandler(this.btnEdit_Click);
I am trying to get value from the databse and assign it to the label using the below line:
lblQuestion.Text = ds.Tables[0].Rows[0]["Question"].ToString();
but it assigns as label.
if (ds.Tables[0].Rows.Count > 0)
{
lblQuestion.Text = ds.Tables[0].Rows[0]["Question"].ToString(); ;
}
UPDATED - Deleted my last info now that you have included the code....
Have you stepped through your code to see if any data is returning?
AKA - is ds.Tables[0].Rows.Count > 0 ?
You are also doing !Page.IsPostBack. This will only call the code and load your labels if it's on the first load.... What about subsequent loads? The labels will return back to whatever they defaulted to in the designer.....
I've put together a test-case in a web app as follows:
ASPX Code-behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var ds = new DataSet();
var table = new DataTable();
table.Columns.Add("Question", typeof(string));
table.Rows.Add(new object[] { "This is the question" });
ds.Tables.Add(table);
lblQuestion.Text = ds.Tables[0].Rows[0]["Question"].ToString();
}
}
ASPX Page:
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="lblQuestion"></asp:Label>
</div>
</form>
This renders out correctly as:
<div>
<span id="lblQuestion">This is the question</span>
</div>
Are you sure you've shown us the code that's actually running?
protected void Page_Load(object sender, EventArgs e)
{
//if (Request.QueryString["QID"] != null)
//{
// Response.Write(Request.QueryString["QID"].ToString());
//}
if (!Page.IsPostBack)
{
int i = Convert.ToInt32(Request.QueryString["QID"]);
// Response.Write(i);
eTutorService ServiceProvider = new eTutorService();
DataSet ds = new DataSet();
ds = ServiceProvider.GetQuestionView(i);
if (ds.Tables[0].Rows.Count > 0)
{
lblQuestion.Text = ds.Tables[0].Rows[0]["Question"].ToString(); ;
lblOption1.Text = ds.Tables[0].Rows[0]["Option1"].ToString();
lblOption2.Text = ds.Tables[0].Rows[0]["Option2"].ToString();
lblOption3.Text = ds.Tables[0].Rows[0]["Option3"].ToString();
lblOption4.Text = ds.Tables[0].Rows[0]["Option4"].ToString();
lblCorrectOption.Text = ds.Tables[0].Rows[0]["CorrectAnswer"].ToString();
lblPaper.Text = ds.Tables[0].Rows[0]["subject"].ToString();
lblDifficultyLevel.Text = ds.Tables[0].Rows[0]["LEVEL_NAME"].ToString();
lblquestionOrder.Text = ds.Tables[0].Rows[0]["QuestionOrder"].ToString();
}
}
}
Its just put label rather than putting database value to the label