Passing c# list to an ASP text field - c#

I was trying to output a single List variable that retrieves data from database via a CodeBehind code to a text field in ASPX:
<asp:TextBox ID="TBCluster" runat="server" CssClass="textbox"></asp:TextBox>
C# is used and the code goes something like this:
public List<shuffleDataList> pullShuffledData(SqlDataReader rdr)
{
List<shuffleDataList> callList = new List<shuffleDataList>();
if (rdr != null)
{
if (rdr.HasRows)
{
while (rdr.Read())
{
callList.Add(new shuffleDataList()
{
cluster = rdr.IsDBNull(5) ? null : rdr.GetString(5),
});
}
}
else
{
Response.Write("<script>alert('the data is null')</script>");
return null;
}
}
return callList;
}
The retrieval of cluster field will occur after a user clicks on a particular button and so my passing the variable goes into like the following:
protected void shuffle_Click(object sender, EventArgs e)
{
getdata();
TBCluster.Text = new shuffleDataList().cluster;
}
However nothing is displayed on the textfield. On the same query, I can display the data on a datagrid view but not on a text field? Any ideas why is this occuring?
Thank you

You don't actually appear to be calling your function. Also, since a Text property is generally a string.. you won't be able to assign a list to it (with any meaningful result). Therefore, I will make a heap of assumptions about your code.. and give you this:
var list = pullShuffledData(someReaderHere);
if (list != null)
TBCluster.Text = string.Join(", ", list.Select(x => x.cluster));

I have finally solved my issue:
string cluster = string.Empty;
DataSet ds = new DataSet();
List<shuffleDataList> list = pullShuffledData(rdr);
foreach(shuffleDataList item in list)
{
cluster = item.cluster;
}
TBCluster.Text = cluster;
It was supposed to be displayed early on but this gridview seems to be clearing the value of pullShuffledData once assigned
//gridviewShuffle.DataSource = pullShuffledData(rdr);
//gridviewShuffle.DataBind();
after commenting out, the cluster value finally appeared on text box. thanks

Related

Data not binded to C# ListView (after second attempt)

I am trying to use a ListView to pull in data from a database. It "works" on the first try if the value exists, but it has a problem when searching for values that don't and then trying again with any other value(even if that other value does exist).
When debugging, I noticed the following:
If I search for a value that doesn't exist in thedatabase, then try to search for one that does, the debugger goes from the line "bValid = true" directly to the method to get the data for the Listview (lstAuthorizations_GetData()). Instead it should go to bindData. It seems like its not processing the bValid = true line. Why would it break here? I've tried changing the line to other variations but no matter what it is, it doesn't seem to process in the right order
Code:
else //default
{
if(string.IsNullOrEmpty(Search_ANumber) && string.IsNullOrEmpty(Search_MemberID))
{
bValid = false;
errorMsg = "Either A Number or M ID are required";
}
else
{
bValid = true;
lstAuthorizations.FindControl("cColumn").Visible = false; // if not in ActiveExceptions, hide column //may want to move this to Line 214
}
}
if (bValid)
{
bindData();
}
protected void bindData()
{
//removeTextBoxValues(); //remove values from Textboxes since you got a response from the DB
ShouldSearch = true;
panelSearchResults.Visible = true;
lstAuthorizations.DataBind();
}
ListView's getdata method:
public IQueryable<Project.Data.databaseView> lstAuthorizations_GetData()
{
try
{
IQueryable<databaseView> query = dbVBA.databaseView.AsQueryable();
if (!String.IsNullOrEmpty(Search_AuthNumber))
{
query = query.Where(m => m.A_Number == Search_ANumber);
}
return query.OrderBy(a=>a.A_Number);
}
aspx:
<asp:ListView ID="lstAuthorizations" runat="server"
ItemPlaceholderID="litPlaceHolder"
ItemType="Project.Data.databaseView" SelectMethod="lstAuthorizations_GetData">
It seems to run the method to get data from the database twice when it actually returns a result (it goes to the lstAuthorizations_GetData() method, then it goes to data bind, then it goes to the lstAuthorizations_GetData() method again). In cases where I try a second value, it goes to the lstAuthorizations_GetData() method, but never goes to bind data.
Anyone know why this is failing?
I had to move hiding/displaying the control AFTER the data was binded. It works now:
if (bValid)
{
bindData();
lstAuthorizations.FindControl("cColumn").Visible = true;

Fill ComboBox on form in a method triggered by a button

First of all, if I click a button the method cbBefüllen will execute.
private void btnEntfernen_Click(object sender, EventArgs e)
{
FeiertageEntfernen entfernen = new FeiertageEntfernen();
entfernen.cbBefüllen();
entfernen.Show();
entfernen.Focus();
}
The following method is just here as an interface between my form and a class. (Please don't ask, in my code I have some good reasons for it ;) ).
public void cbBefüllen()
{
database.cbFeiertagebefüllen();
}
The method cbFeiertagebefüllen (tries to) fills my ComboBox, which is located in the form "feiertagentfernen".
public void cbFeiertagebefüllen()
{
FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
string Query = #"select bezeichnung from feiertage";
using (var command = new SQLiteCommand(Query, sqlite_conn))
{
if (sqlite_conn.State != ConnectionState.Open)
{
sqlite_conn.Open();
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string übergabe = reader.GetString(0);
feiertagentfernen.cbFeiertag.Items.Add(übergabe);
}
}
}
}
But after this whole process my ComboBox is still empty. The reader in the last picture picks the correct value from the database, but somehow it won't write it into the ComboBox.
Your problem is in this line:
FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
in your cbFeiertagebefüllen()
You make a new form but you want your combo box from the form from the 1st piece of code to be filled. To fix this you could pass along an instance of the form to the filling method.
The updated 2 pieces of code will be (first piece can be left alone):
In cbBefullen:
database.cbFeiertagebefüllen(this);
//'this' means we're passing along the form as parameter
In cbFeiertagebefüllen:
public void cbFeiertagebefüllen(FeiertageEntfernen feiertagentfernen)
{
string Query = #"select bezeichnung from feiertage";
using (var command = new SQLiteCommand(Query, sqlite_conn))
{
if (sqlite_conn.State != ConnectionState.Open)
{
sqlite_conn.Open();
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string übergabe = reader.GetString(0);
feiertagentfernen.cbFeiertag.Items.Add(übergabe);
}
}
}
}
The FeiertageEntfernen form instance on which you're filling the cbFeiertag combo box in cbFeiertagebefüllen() is not the form's instance you're showing after that. You need to pass the entfernen instance to cbFeiertagebefüllen():
public void cbBefüllen()
{
database.cbFeiertagebefüllen(this);
}
public void cbFeiertagebefüllen(FeiertageEntfernen feiertagentfernen)
{
// Use the passed in instance instead of a newly created one
//FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
string Query = #"select bezeichnung from feiertage";
// ....................
}
For this to work, the ComboBox which you need to fill, should be globally declared, i.e. outside the scope of your functions. The rest is probably fine. Also it's better if you get the values you need to display in the comboBox to the main form rather than calling the ComboBox instance 2 levels deeper.
I know this is a little confusing, in simple words, What you could do is, fill the values(descriptions of the holidays) from the DataBase into a list. Make your functions return this list when called. And finally where the ComboBox is declared, you could just add that list as the source of the ComboBox
It looks like you are adding the options to the combo box, but you are not actually setting the selected item.
To do so, you need to set cbFeiertag.SelectedIndex or cbFeiertag.SelectedValue.

Transfer items between drop-down lists in different webForms

I am a not experienced programmer, just a rookie enthusiast.
I have a webForm where I add items to a drop-down list.
There is another webform that contains another drop-down list, I want this second "ddl" to display the items I added to the "first ddl".
After not succeeding with public properties, I tried to get this accomplished in the most straight fashion:
In designer.cs change the first "ddl" from protected global to public.
On the second webForm I wrote:
WebForm3 wf_ConfigurationPage = new WebForm3();
And a short function with these lines:
ddl_ingenieros.DataSource = wf_ConfigurationPage.ddl_Engineers;
ddl_ingenieros.DataBind();
I am calling the function from PageLoad but unfortunately the "ddl" is not showing the items from its "DataSource ddl".
Also, when I switch pages, the items I added to the original "ddl" just disappear.
Can you help me get these 2 issues resolved?
I managed to get something similiar done for a gridview as follows:
On the webform where the original gridview is located:
static DataSet DS;
static DataTable tableRequests;
/* -------------- Public Properties ---------------- */
public DataSet currentList //Allows access from other pages.
{
get {
return DS;
}
}
public DataTable currentTable {
get {
return tableRequests;
}
}
On the second webForm I wanted to show the gridview:
WebForm1 wf_ActiveReq = new WebForm1();
Then a short function that I call from PageLoad, which has these lines:
gv_results.DataSource = wf_ActiveReq.currentList;
gv_results.DataBind();
I was unable to do the same with the ddls because unlike the DataSet and the Data Table, the ddl was created from designer view, when I tried to declared them in the "code behind" of the webForm where the "original" ddl exists I got an error about the object being duplicate, which makes sense.
Thanks for your time
#Erkaner
In first webForm:
static List<string> myItems = new List<string>();
protected void btn_add_Click(object sender, EventArgs e)
{
if (Session["myItems"] != null)
{
myItems = (List<string>) Session["myItems"];
}
myItems.Add(txt_newAdmin.Text);
ddl_Engineers.DataSource = myItems;
ddl_Engineers.DataBind();
txt_newAdmin.Text = "";
}
In second webForm, I wrote a function I call from pageLoad:
private void pull_engineersList()
{
ddl_ingenieros.DataSource = Session["myItems"];
ddl_ingenieros.DataBind();
}
Thanks again!
Why not use Session :
In the first page:
Session["myddlstore"] = myFirstDDL.DataSource;
and in the second page
mySecondDDL.DataSource = Session["myddlstore"];
mySecondDDL.DataBind();
UPDATE
If the dropdowlinst items are added by the user, then you can implement something like this in the button click that adds item to the dropdownlist:
List<string> myitems = new List<string> ();
if(Session["myitems"] != null)
{
myitems = (List<string>) Session["myitems"];
}
myitems.Add(txt_NewItem.Text);
myFirstDDL.DataSource = myitems;
myFirstDDL.DataBind();
and, similarly. in the second page
mySecondDDL.DataSource = Session["myitems"];
mySecondDDL.DataBind();
Session["myitems"] = myitems;
If you store a more complex object in dropdownlist, I would define a class that represents the complex object, and still use the approach described above (List<ObjectType>).

C# Code-behind control form execution

I have a form that I would like to reuse for both adding a new record and editing an existing record. I am able to successfully load the page with the relevant data when I select a record from a GridView and I am able to update the db record appropriately. However, my issue is trying to use the form for both executions. Here is my logic in code behind: (I assign a session variable when I click on the row in GridView and this does work successfully)
protected void Page_Load(object sender, EventArgs e)
{
resultOutput.Visible = false;//Output results as to whether or not a record was added successfully is automatically hidden at page load
//Checking to see if session variable has been created
if (Session["editID"] != null)
{
//Create objects to get recipe data
dbCRUD db = new dbCRUD();
Recipe editRecipe = new Recipe();
//Grabbing session ID and assigning to a variable in order to remove the session variable
var id = Convert.ToInt32(Session["editID"]);
Session.Remove("editID");
//Call method to retrieve db data
editRecipe = db.SelectRecord(id);
//Populate results to text boxes
recordID.Text = id.ToString();
addName.Text = editRecipe.Name;
addTypeDDL.SelectedValue = editRecipe.Meal;
addDifficultyDDL.SelectedValue = editRecipe.Difficulty;
addCookTime.Text = editRecipe.Cook_Time.ToString();
addDirections.Text = editRecipe.Directions;
//Change Button Text
submitRecord.Visible = false;
changeRecord.Visible = true;
//Change Title Text
addEditTitle.Text = "Edit Recipe";
}
}
protected void submitRecord_Click(object sender, EventArgs e)
{
//Variables for execution results
var modified = "";
int returned = 0;
//Creating the recipe Object to pull the values from the form and
//send the recipe object as a parameter to the method containing insert stored procedure
//depending on Add or Edit
Recipe recipe = new Recipe();
recipe.Name = addName.Text;
recipe.Meal = addTypeDDL.Text;
recipe.Difficulty = addDifficultyDDL.Text;
recipe.Cook_Time = int.Parse(addCookTime.Text);
recipe.Directions = addDirections.Text;
//Creating object to access insert method
dbCRUD newRecord = new dbCRUD();
//Checking to see if the page is loaded for edit or new addition
if (Session["editID"] != null)
{
//If recordID exists, recipe will be passed as to UpdateRecord method
recipe.Recipe_ID = int.Parse(recordID.Text);
returned = newRecord.UpdateRecord(recipe);
modified = "has been edited.";
Session.Remove("editID");
}
else
{
//If recordID does not exist, record will be passed to InsertRecord method (new recipe)
returned = newRecord.InsertRecord(recipe);
modified = "added";
}
//Method returns 0 if successful, 1 if sql error, 2 if other error
if (returned == 1)
{
resultOutput.Text = "There was an sql exception";
resultOutput.Visible = true;
}
else if (returned == 2)
{
resultOutput.Text = "There was a non sql exception";
resultOutput.Visible = true;
}
else
{
resultOutput.Text = "\"" + addName.Text + "\" recipe " + modified;
resultOutput.Visible = true;
}
}
I have issues on the if(Session["editID"] != null) line - I am always moved to the else logic and the if logic never runs.
Here is my click method in the GridView:
protected void Grid_Recipe_SelectedIndexChanged(object sender, EventArgs e)
{
int index = Convert.ToInt32(Grid_Recipe.SelectedDataKey.Value);
Session["editID"] = index;
Response.Redirect("addRecord.aspx");
}
My question is how can I control execution during the submitRecord_Click event so that I call the appropriate method. Thanks!
Have you considered using
if(Page.IsPostBack)
{
code here
}
To detect whether you are posting back to the page? Then you could check your value of the item. I see no reason the code shouldn't be in the Session variable - have you tried putting a breakpoint in there to see if the code actually gets in there?
Also does your addRecord.aspx just add the record? If so, just add the record in this class, but use the PostBack check to see. Could you just make sure you are saving in the right context aswell:
// Outside of Web Forms page class, use HttpContext.Current.
HttpContext context = HttpContext.Current;
context.Session["editID"] = index;
...
int Id = (string)(context.Session["editID"]);
I was able to figure out my issue - which actually turned into two issues. First, I had to put my Page Load logic in a if(!IsPostBack) statement because I could not edit the page. Reason being is I was loading the originally posted data to the form on page load, which executed before my logic. Adding the if(!IsPostBack) control statement fixed this issue. From there, I'm still using a session variable to control code behind logic, only I made sure keep my session variable only between the form and the gridview. Basically, when the gridview loads and it is not a post back, the session variable is cleared. This let's me set a new session variable when I click on a row and then the session variable is cleared once I return to the grid to see the results. Thanks for the help!

Which is the recommended way to fill all controls on a Web Form when user selects a record?

I have a GridView control which shows a list of all employees. When user selects any employee from this list, the record is shown on a Web Form with all input controls pre-filled with the values.
I want to know any good approach to do this. Should I bind all input controls to any SqlDataSource or should I re-populate all input controls by picking values from the DataSet.
First you add the select button on your GridView as:
<asp:ButtonField Text="Select" CommandName="ViewMe" ButtonType="Button" />
then you add the OnRowCommand="RowCommand" property on GridView to call this function when the button is clicked and on code behind the function:
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
// if the ViewMe command is fired
if (e.CommandName == "ViewMe")
{
// go to find the index on the grid view
int iTheIndexNow;
if (int.TryParse(e.CommandArgument.ToString(), out iTheIndexNow))
{
// Set and highlight the selected
TheGridView.SelectedIndex = iTheIndexNow;
// do we have the table data id ?
if (TheGridView.SelectedValue != null)
{
// now load the controls data using this id
LoadValuesFromDatabaseToControls(TheGridView.SelectedValue);
}
}
}
}
I prefer this way of command button because you can add more commands than the select, or edit, even the delete or copy... the just index change can be done for any reason (eg by changing page) and is also need again the select.
I use the subsonic 2 DAL for loading the data from the database. A sample code from my programs is:
void LoadValuesFromDatabaseToControls(string editID)
{
// Load it from database
AthUserMaiListName OneRow = new AthUserMaiListName(editID);
if (OneRow.IsNotExist)
{
// a custom control that show messages on top.
uResult.addMsg("Fail to load id " + editID, MsgType.error);
// close the view of the controls
dbViewPanel.Visible = false;
}
else // else we have the data and go for show them
{
// show this panel that contains the controls.
dbViewPanel.Visible = true;
// I keep my current edit id
lblID.Text = editID;
// just be sure that the select exist on DrowDownList
MyUtils.SelectDropDownList(ddlEventType, OneRow.CAddedFrom);
txtEmail.Text = OneRow.CEmail;
txtFirstName.Text = OneRow.CFirstName;
txtLastName.Text = OneRow.CLastName;
txtInsideTitle.Text = OneRow.CInsideTitle;
txtCompanyName.Text = OneRow.CCompanyName;
txtCreated.Text = DateTimeRender(OneRow.CreatedOn);
txtModified.Text = DateTimeRender(OneRow.ModifiedOn);
}
}
I used this code in my application-
A better approach would call to this mothod on gridview_select_index_change() event
private void PickValues(int SerialNum)
{
DataSet ds = new DataSet();
try
{
string Query = "SELECT * FROM tw_main WHERE sno = " + SerialNum;
ds = reuse.ReturnDataSet(Query, "Scheme");
//Add Scheme Code to new Session Variable
Session.Add("SerialNumber", ds.Tables[0].Rows[0]["sno"].ToString());
//Set Update Flag
TaskFlag = "UPDATE";
//Fill values of selected record on the Entry Form
if (ds.Tables[0].Rows[0]["schm_code"].ToString().Length > 0)
lblSchemeCode.Text = ds.Tables[0].Rows[0]["schm_code"].ToString();
ddlType.SelectedValue = ds.Tables[0].Rows[0]["schemetype"].ToString(); ddlDistrict.Text = ds.Tables[0].Rows[0]["dist_nm"].ToString(); ddlBlock.Text = ds.Tables[0].Rows[0]["block_nm"].ToString();
txtSchemeName.Text = ds.Tables[0].Rows[0]["schm_nm"].ToString();
txtPopulation2001.Text = ds.Tables[0].Rows[0]["population_2001"].ToString();
txtSupplySource.Text = ds.Tables[0].Rows[0]["supply_source"].ToString();
txtApprovalYear.Text = ds.Tables[0].Rows[0]["yr_approval"].ToString();
txtApprovalLetterNum.Text = ds.Tables[0].Rows[0]["approval_letter_num"].ToString();
txtApprovalAmount.Text = ds.Tables[0].Rows[0]["sch_apr_amt"].ToString();
txtWaitedLetterNum.Text = ds.Tables[0].Rows[0]["sch_waited_details"].ToString();
txtSchTransferLetterNum.Text = ds.Tables[0].Rows[0]["schm_trans_details"].ToString();
txtSchTransferDate.Text = ds.Tables[0].Rows[0]["schm_trans_date"].ToString();
txtOtherRemarks.Text = ds.Tables[0].Rows[0]["remarks"].ToString();
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "Warning", "alert('" + ex.Message.ToString() + "');",true);
}
finally
{
ds.Dispose();
gridSerialNo = 0;
}
}
EDIT
There might be better approach to do so but this works certainly fine.
The way I would perform this task since you want to create a data access layer is to create a class which has all the properties
Class:
public class tw_main
{
public string SchemeCode {get;set;}
}
DAL:
public class dal
{
public tw_main getSelectedValue(pass the parameters required by the method)
{
//your connection and query code
var twmain = new tw_main();
twmain.SchemaCode = ds.Tables[0].Rows[0]["schm_code"].ToString();
return twmain;
}
}
Web Page:
//depending upon where you add this a reference may need to be imported (using) to the namespace
var dalObj = new dal();
var tw = dalObj.getSelectedValue();
lblSchemeCode.Text = tw.SchemaCode;

Categories

Resources