First and foremost, I'm pretty new to programming, so attention to detail is appreciated.
I've currently got an asp checkbox list that receives data from an SQL table. I'm encountering a problem where if there's 2 items that are exactly the same, my remove function will remove both items. The following is the code for that:
protected void btn_remove_Click(object sender, EventArgs e)
{
for (int i = 0; i < UPCList.Items.Count; i++)
{
if (UPCList.Items[i].Selected)
{
var item = UPCList.Items[i];
var frcID = item.Value;
_itemNumberRepository.Delete(frcID);
}
}
Response.Redirect("WebForm2.aspx");
Response.End();
}
public string Delete(string itemCode)
{
string connectionString = foobar
Int32 returnDeleted = 0;
string deleteUpcCode =
"DELETE FROM compare1 "
+ string.Format("WHERE itemcode = '{0}'",itemCode);
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(deleteUpcCode, connection);
command.Connection.Open();
returnDeleted = command.ExecuteNonQuery();
command.Connection.Close();
}
return returnDeleted.ToString();
}
I've been told to use Auto Incrementing ID from SQL so that each row will have a unique ID so I can delete only the selected lines. However, I don't even have a clue how to do that. I've already turned on the identity option in SQL for the itemcode column, but aside from that, I'm lost. How do I go about using that ID to delete only selected items from the checkbox list in asp?
When you say the items are "exactly the same", do you mean that they have the same item code? And item codes are allowed to be duplicated in your system (i.e. is that the correct business rule)?
If so, that's why you need a auto-generated ID for each line, so that each row is unique. Which means that you need to use that ID in your DELETE query instead of the item code.
Typically, in a (ASP.NET) web app, this sort of thing is done with a "grid". You can use a GridView with two columns: one is a checkbox and another column is just a label showing the item code. Each row is bound to the ID field.
So, I recommend that you start by checking out GridView (there's lots of examples out there on the web): MSDN documentation for GridView
Related
When I use the code below, I remove the datatable values, but the data table structure still exists and displays empty fields (see pics) with the DOM explorer showing an empty table and table rows.
How can I clear the datatable values and the table itself? This way when I repopulate search again, the empty smaller table isn't present?
lvwOutput.Items.Clear();
lvwOutput.DataSource = null;
lvwOutput.DataBind();
Before
After items.clear and datasource = null
This is ridiculous and I believe there is a better way to do this, but the never ending server/client battle makes this harder than it should be. My listview binded to a datatable is called lvwOutput.
In my btnClear I had to put the following. You cannot hide the element or clear the items in the server side asp code for this to work
ScriptManager.RegisterStartupScript(Page, GetType(), "emptyTable", "javascript:emptyTableRows(); ", true);
In my javascript code I had to put the following, this clears the client code
function emptyTableRows(){
var tableHeaderRowCount = 0;
var table = document.getElementById('lvwOutputTable');
var rowCount = table.rows.length;
for (var i = tableHeaderRowCount; i < rowCount; i++) {
table.deleteRow(tableHeaderRowCount);
}
}
And then in the portion of my code that would display the listview and datatable when the user initiates another sql search. This clears the server side.
lvwOutput.Items.Clear();
lvwOutput.DataSource = null;
lvwOutput.DataBind();
You can create a property the stores the data table in session that way you can access it during the click event.
DataTable dtbleDataSource
{
get
{
return Session["dataSource"] as DataTable
}
set
{
Session["dataSource"] = value;
}
}
In your click event you can say:
dtbleDataSource.Reset();
I have a dropdown in asp.net which fills with Agent list. now agent list is 30,000. So I want to keep all the data in cache as we dont need to fill the dropdown again and again from database. How to achieve this by caching. Please guide
Suppose you have Cache varriable, then you have to convert it to DataTable,
DataTable tblCategories = (DataTable) Cache["Categories"];
and , then check, if still Datatable empty, then fetch from database using LoadCategoryInDropDownList() function which takes data from databse.
if (tblCategories == null)
{
tblCategories = new DataTable();
tblCategories=objDac.LoadCategoryInDropDownList();
// It inserts new row in filled datatable.
//This new row contains static data for user
//instruction Text such as" Select the Item"
DataRow dr=tblCategories.NewRow();
dr["CategoryID"]=0;
dr["CategoryName"]="--Select Item--";
tblCategories.Rows.InsertAt(dr,0);
//Cache The DataTable in a Cache Memory for duration of one hour...
Cache.Insert("Categories", tblCategories, null,
DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
}
then bind dropdown to datatable
DropDownList1.DataSource = tblCategories
DropDownList1.DataTextField ="A Descriptive Field from Table";
DropDownList1.DataValueField="A key / Value Field from Table";
DropDownList1.DataBind();
You can refer here http://www.codeproject.com/Articles/10033/A-generic-loading-of-data-in-a-DropDownList-using
Do you use particular cache framework?
.Net 4.5 has MemoryCache class you can use.
Example:
ObjectCache cache = MemoryCache.Default;
public Object GetCacheItem(string key)
{
return cache[key] as Object;
}
public void SaveCache(string key, Object value)
{
cache[key] = value;
}
public void RemoveCacheItem(string key)
{
if (cache.Contains(key))
cache.Remove(key);
}
Once you have your caching setup in a class, you can use it to cache your Agent lists. Then, load it to drop down list.
WARNING : Be very careful when using caching. Make sure you clear the cache at the end of certain life cycle. I have seen a case where IIS application pool using all of the memory in a server, so app pool has to be restarted every now and then.
I am a sever call in rowdatabound event. The page loads slowly because of multiple sever calls. How can i make the server call in page load. The queried data have to be accessed in row data bound. Any help appreciated....
protected void Grid_course_RowDataBound(object sender, GridViewRowEventArgs e)
{
/*Tooltip.............................................*/
connect con = new connect(date);
Boolean bo = false;
IList<connect.Courses> ob = con.getCoursedetails();
Dictionary<string, string> tooltip = new Dictionary<string, string>();
for (int i = 0; i < ob.Count; i++)
{
if (!tooltip.ContainsKey(ob[i].Name.ToString()))
tooltip.Add(ob[i].Name.ToString(), ob[i].Course_Description__c.ToString());
}
------------------
--------------------
}
The class connect connecting to salesforce and retrieving data.For each row bound it will query data from salesforce.
For every row you are using
con.getCoursedetails();
Do you really want to show the entire records for every row?
As I can see, you are not passing any parameter to the function, so why cannot you call the method once and use the same result for every row as you are doing.
No need to get the data from database fro every row otherwise you need to pass some parameter to get the result only related to that row and that will get less record and your page will work better.
i have created dynamic listboxes (4 to 10) in ASP.NET.
and my question is , How do i find the dynamically created listboxes using c#?
thanks
Sure... and i appreciate your help . below code i am using for creating dynamic LB
protected void btndyfilter_Click(object sender, EventArgs e)
{
int numberOfListBox = lbFilter.GetSelectedIndices().Length;
string lbname = lbFilter.SelectedValue;
for (int i = 0; i < numberOfListBox; i++)
{
ListBox listb = new ListBox();
ListItem lItem = new ListItem();
listb.SelectionMode = System.Web.UI.WebControls.ListSelectionMode.Multiple;
listb.Height = 150;
listb.Width = 200;
lItem.Value = i.ToString();
lItem.Text = lbname;
listb.Items.Add(lItem);
panFilter.Controls.Add(listb);
//once we created the LB dynamically i need to populate each LB with the corresponding values
connstr2 = System.Configuration.ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
conn2.ConnectionString = connstr2;
conn2.Open();
CubeCollection CubeList = conn2.Cubes;
string cb = ddlCubeList.SelectedItem.Text;
//need to remove the Hardcoded Code
foreach (Member dimem in CubeList[cb].Dimensions["Date"].Hierarchies["Calendar Date"].Levels["Date"].GetMembers())
{
ListItem Memlist = new ListItem();
Memlist.Text = dimem.UniqueName;
lbFilter.Items.Add(Memlist);
}
}
panFilter.Visible = true;
panCubeDef.Visible = true;
}
so this will create the LB i believe :)... and Inside the commented code i need to use to populate for each LB item ..perhaps it bit hardcoded which i need to remove. so i all dynamic LBs are populated then the selected items from all LBs will come into the where clause in my MDX query..hope i did not confuse you
There is 2 way either you can store dynamic control detail with dictionary or just find when you want to use it using some code like this
Control GetControlByName(string Name)
{
foreach(Control c in this.Controls)
if(c.Name == Name)
return c;
return null;
}
while generating ListBox dynamically, give ListBox ID as:
lstBoxNo1, lstBoxNo2. lstBoxNo3 etc. where 1,2,3(no) will be from count.
like
int count=1;
generate listbox control
listboxid=lastBoxNo+count;
count++
`by doing this, u have control over id's.
else use
http://stackoverflow.com/questions/3731007/using-findcontrol-to-find-control
using this link to understand findcontrol.
The points that you wont to find that dynamic controls are.
The moment you first render the page.
On every other post back.
In the case of 1, then you better keep a variable on your page that keep that creations.
In the case of 2, when you have post back, you need to store somehow the creations of your control in the page when you render it. One good place is to keep that information on the viewstate.
You can also on the post back, just to check if you have any post back valued from controls that you have named with a serial numbering starting from 1, eg You start looking if you have post back from ControlName_1, then ControlName_2, and when you not found any other value you end.
I am using asp.net and I am trying to save checkbox values into a database. Multiple checkboxes may be entered into the same field in the database. So for instance I have two checkboxes with names "Comma" and "Hyphen" and if the user checks both of these then the database will store the values ',','-'. How do you do this?
thanks
To save multiple values into the same column I'd recommend using a flag enumeration. Here is a code sample using checkboxes.
If you really have to store the values in a comma-delimited format, might try something like this:
List<string> values = new List<string>();
if (cbComma.Checked) {
values.Add("','");
}
...
string result = values.ToArray().Join(",");
I'd agree with David Thomas Garcia's recommendation if you can save the value to the database using the enumeration (as an int or whatever was appropriate for the amount of options you'll have).
If that's not an option though, and you are bound to storing them in the database as a string of characters I'd do something like the following:
private void LoadData()
{
string dbVal = DataAccess.GetDbVal(); //Get your value from the database.
chkComma.Checked = dbVal.Contains(",");
chkDash.Checked = dbVal.Contains("-");
}
private void SaveData()
{
string dbVal = "";
if(chkComma.Checked)
dbVal += ",";
if(chkDash.Checked)
dbVal += "-";
DataAccess.SaveDbVal(dbVal); //Send the value of dbVal to your data layer to be saved.
}
Note that this does not include any separation of the values to be saved in the value stored in the database, but if you needed that you could use a List and do what David Thomas Garcia mentioned with the .ToArray().Join(","); in the SaveData() and in the LoadData() just make dbVal a List and the syntax doesn't need change.