I have web Service method that returns value of one column of a table. I want add that value to my drop down list. Is there any easy way to do it.
Here is my web method that returns all conference_name in conference table.
[WebMethod(Description = "Retrieves all Conference")]
public DataSet GetAllConference()
{
DataSet dataSet = new DataSet();
// Create connection object
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT conference_name FROM Conference";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "Conference");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables.Count <= 0)
return null;
else
return dataSet;
}
On user side there will be one dropdown list. How can i add the value return by the web method to the dropdown list.
You need to add web reference of web service in order to call the method, You may read this post to know how add reference, After adding reference you can call the method adn fill the drop down by the code given below,
DataSet ds = wsObject.GetAllConference();
if(ds.Tables.Count > 0)
{
ddlist.DataTextField = "conference_name";
ddlist.DataValueField = "conference_name"; //Change field to one you want.
//ddlist.DataValueField = "IDColumnInTheDataTable"; //un comment after give right column name
ddlist.DataSource = ds.Tables[0];
ddlist.DataBind();
}
Related
Please bear with me as I'm rather new to this.
I'm trying to iterate through a recordset using DataReader object, and do something at each iteration, but it doesn't seem to be getting passed the first record. I essentially want to look at each record and then assign a specific image to a specified location based on the data in a column in the recordset.
I'm using Visual Studio 2019 and using OleDataReader to read Access table. I've got the command object working properly, just can't seem to get passed the first record.
this is the method definition in my class
//Giving string variable names to the virtual paths of the images
private string whitePallet = "~/images/White.jpg";
private string redPallet = "~/images/Red.jpg";
private string bluePallet = "~/images/Blue.jpg";
private string blackPallet = "~/images/Black.jpg";
private string greenPallet = "~/images/Green.jpg";
private string racetrack = "~/images/Racetrack.jpeg";
public string Racetrack { get => racetrack; set => racetrack = value; }
public string OpenConnection(string connectString, String selectString)
{
using (OleDbConnection cn = new OleDbConnection(connectString))
{
cn.Open(); //Open the connection.
OleDbCommand cmd = new OleDbCommand(selectString, cn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string pallet;
if (reader["Status"].ToString() == "Blocked Location")
{
pallet = blackPallet;
return pallet;
}
if (reader["Status"].ToString() == "AP Purge")
{
pallet = redPallet;
return pallet;
}
if (reader["Status"].ToString() == "Open")
{
pallet = whitePallet;
return pallet;
}
if (reader["Status"].ToString() == "Order Complete")
{
pallet = greenPallet;
return pallet;
}
if (reader["Status"].ToString() == "Pallet Full")
{
pallet = bluePallet;
return pallet;
}
}
//Close the reader and the related connection.
reader.Close();
return null;
}
}
this is the instantiation of the class/method
'''
Definitions defs = new Definitions();
Image imgRacetrack = Image.FromFile(Server.MapPath(defs.Racetrack));
//Creating image panel to draw upon using w/h of racetrack image
Image img = new Bitmap(imgRacetrack.Width, imgRacetrack.Height);
using (Graphics gr = Graphics.FromImage(img))
{
//Background image
gr.DrawImage(imgRacetrack, new Point(0, 0));
//Defining the points on the left side:
Point p1 = new Point(125, 50);
Image imgPallet = Image.FromFile(Server.MapPath(defs.OpenConnection(connectString,selectString)));
gr.DrawImage(imgPallet, p1);
Point p2 = new Point(125, 100);
Image imgPallet2 = enter code hereImage.FromFile(Server.MapPath(defs.OpenConnection(connectString, selectString)));
gr.DrawImage(imgPallet2, p2);
}
I'm expecting to iterate through each record and then place the image with the correct color into the correct position, but it's only giving the results to each point/location based on the very first record only. What's wrong with my logic??
You declare pallet string pallet; then have several if statements in which you return pallet;.
First, you want to return a string, but you're doing
pallet = blackPallet; // pallet will not be a string.
pallet = "blackPallet"; // pallet will be a string.
Second, when you say return..., you leave the method; you don't continue after that, you are saying you are done - return this value and stop.
So you need to read the value from each row and store them, then return the collection of values. Then you can loop through the collection and plug in each value as needed.
That's one way. I didn't study what you have in complete detail so there might be a better way. Hope that's enough for now.
My code is
public Emp GetEmpByEmpno(int empno)
{
using (con)
{
if (con.State == ConnectionState.Closed)
{
con.ConnectionString = constr;
con.Open();
}
cmd.CommandText = "sp_emp_GetempByEmpno";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#eno",empno);
dr=cmd.ExecuteReader();
Emp obj=null;
while(dr.Read())
{
obj=new Emp();
obj.Empno=int.Parse(dr["Empno"].ToString());
obj.Ename=dr["Ename"].ToString();
obj.Sal=dr["Sal"].ToString();
obj.Deptno=int.Parse(dr["Deptno"].ToString());
}
return obj;
}
}
Here I fetch the record based on employee number, whenever i pass empno in textbox search button onClick, the respective employee should display in grid view. How can i bind the object to grid view?
Employee obj=EmpDeptBus.GetEmployeeByEmpno(int.Parse(txtEmpno.Text));
gvemp.DataSource = c;
gvemp.DataBind();
You should be able to just say
gvemp.DataSource = obj;
That's really all you need to do to bind the object.
Also, change your
while(dr.Read())
to
if(dr.Read())
You're only expecting one record so only fetch one. Also put your return obj outside your using to make sure everything is properly disposed before you return to the calling function.
Try making sure that txtEmpno.Text holds an int value before you attempt to pass it to this method or it will blow up. Never, ever trust user input. You could do something like:
int empNo = 0;
if(int.TryParse(txtEmpNo.Text.Trim(), out empNo)
{
// then call the function and bind your grid using the empNo as the
// variable holding the employee number.
}
else
{
// otherwise handle the fact that the user entered a non-numeric.
}
I am trying to grab multiple values from a checkboxlist and add them to a list, But checked values are always false even though the list contains appropriate count value.
code to populate:
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
HelpingOthersEntities helpData = new HelpingOthersEntities();
List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>();
locCkBox.DataSource = theDataSet;
locCkBox.DataTextField = "slAddress";
locCkBox.DataValueField = "storeLocationID";
locCkBox.DataBind();
code for adding to list:
List<int> locList = new List<int>();
for (int x = 0; x < locCkBox.Items.Count; x++){
if(locCkBox.Items[x].Selected){
locList.Add(int.Parse(locCkBox.Items[x].Value));
}
}
The problem I am having is that I cannot get into items.selected
my value is always false.
I have tried populating the checkboxes from postback but i get the same result. My list gives me the appropriate .Count amount of values, but items.selected = false?
I have tried a foreach loop to add to list as well but I get the same results over and over. Am i missing an event or something?
I'm going to take a guess here and say that your code that does the population stuff is being called in the pageload event, so you have something like the following.
private void Page_Load()
{
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
HelpingOthersEntities helpData = new HelpingOthersEntities();
List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>();
locCkBox.DataSource = theDataSet;
locCkBox.DataTextField = "slAddress";
locCkBox.DataValueField = "storeLocationID";
locCkBox.DataBind();
}
If that's the case then your effectively writing over the postback data on each request. To sort this out you need to only perform the databinding when its not a postback, so you need to change the above code to
private void Page_Load()
{
if (!IsPostBack)
{
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
HelpingOthersEntities helpData = new HelpingOthersEntities();
List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>();
locCkBox.DataSource = theDataSet;
locCkBox.DataTextField = "slAddress";
locCkBox.DataValueField = "storeLocationID";
locCkBox.DataBind();
}
}
You should then be able to test the Selected property of the items. I'd also probably change the code your using to test for the selected to something like
List<int> locList = new List<int>();
foreach(var item in locCkBox.Items)
{
if(item.Selected)
{
locList.Add(int.Parse(item.Value));
}
}
or if your on a .NET version with LINQ available
List<int> locList = new List<int>();
(from item in locCkBox.Items where item.Selected == true select item).ForEach(i => locList.Add(i.Value));
Make sure while binding the checkboxlist in page load you have set this check.
if (!Page.IsPostBack)
{
...bind your data
}
This should do the trick.
I have a web page that needs to update multiple records. This page gets all the information and then begins a transaction sending multiple UPDATE queries to the data base.
foreach row
{
Prepare the query
Hashtable Item = new Hashtable();
Item.Add("Id", Id);
Item.Add("Field1", Field1);
Item.Add("Field2", Field2);
Item.Add("Field3", Field3);
...
}
Then we launch the ytransaction
DO CHANGES()
public void execute_NonQuery_procedure_transaction(string StoredProcedure, List<Hashtable> Params)
{
using (MySqlConnection oConnection = new MySqlConnection(ConfigurationManager.AppSettings[DB]))
{
MySqlTransaction oTransaction;
bool HasErrors = false;
oConnection.Open();
oTransaction = oConnection.BeginTransaction();
try
{
MySqlCommand oCommand = new MySqlCommand(StoredProcedure, oConnection);
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.Transaction = oTransaction;
foreach (Hashtable hParams in Params)
{
oCommand.Parameters.Clear();
IDictionaryEnumerator en = hParams.GetEnumerator();
while (en.MoveNext())
{
oCommand.Parameters.AddWithValue("_" + en.Key.ToString(), en.Value);
oCommand.Parameters["_" + en.Key.ToString()].Direction = ParameterDirection.Input;
}
oCommand.ExecuteNonQuery();
}
}
catch (Exception e)
{
HasErrors = true;
throw e;
}
finally
{
if (HasErrors)
oTransaction.Rollback();
else
oTransaction.Commit();
oConnection.Close();
}
}
}
Is there another way to do this or this is the most efficient way?
It depends on the situation, like if you have multiple row updates or adding new rows or deleting some rows or a combination of these, which modifies the database table then, the efficient way to do this is to have Batch Update...
Please go through this link Batch Update
Hope this helps...
it looks fine to me, you could eventually do not clear the Command.Parameters list but just assign the values on following iterations but probably this leads to no visible improvements.
pay attention your throw is wrong, in C# don't use throw e; but simply throw;.
enter code herehi. i am trying to implment custom paging in datalist control .
and i am using Pagedatasource to schive this one
PagedDataSource objPage = new PagedDataSource();
try
{
datatable ds= (datatable)viewstate["dtimages"]
objPage.AllowPaging = true;
//Assigning the datasource to the 'objPage' object.
objPage.DataSource = ds.Dataset.Tables["Gallery"].ToString();
//Setting the Pagesize
objPage.PageSize = 8;
dlGallery.DataSource = objPage;
dlGallery.DataKeyField = "Image_ID";
**dlGallery.DataBind();// getting error**
}
catch(Exception ex)
{
throw ex;
}
Cannot compute Count for a data source that does not implement ICollection.
why is this happening does any one can help me out
thank you
You're setting your Data Source to a string by calling ToString().
It should be:
objPage.DataSource = ds.Dataset.Tables["Gallery"];