I have a listbox with a list of items that get loaded when you navigate to a certain page. Then I have an on click that passes parameters to an AddProducts method. That method is what loops through all selected items and inserts values from the fields filled in as well as takes the values from the listItems and adds them as parameters to a stored procedure.
The problem I'm running into is that when looping through the listItems
if(selectedItem.Selected) is returning false, but in my method where I load the listbox I initialize a SelectedValue so I'm not sure why it's giving me the error message I have for no selected items. I was able to get it to work yesterday before I moved LoadListBoxCategories outside of LoadAddData but unsure as to why that would have any effect to if(listItem.Selected).
I'm relatively new to asp.net so any help/ explanation as to why my code isn't working is extremely appreciated. I've spent the last three days trying to figure this out and haven't found a solution that works.
Code:
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session[IS_LOGGED_IN] == null)
{
Response.Redirect("/utilities/companydata/login.aspx", true);
return;
}
gvTextInputs.RowEditing += new GridViewEditEventHandler(gvTextInputs_RowEditing);
if (!IsPostBack)
{
string pageId = Request.QueryString["pageid"];
string productId = Request.QueryString["productid"];
/* Add Mode */
if (!string.IsNullOrEmpty(pageId))
{
SetMode(MODE_ADD, "");
LoadAddData(pageId);
LoadListBoxCategories(pageId);
}
else if (!string.IsNullOrEmpty(productId))
{
string imageServer;
if (LoadProductData(productId, out imageServer))
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
SetMode(MODE_EDIT, imageServer);
SetImageServer(imageServer);
}
else
{
//TO DO - Return Error
}
}
}
else
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
}
}
Load ListBox:
private void LoadListBoxCategories(string pageId)
{
listBoxCategories.Visible = true;
//This gets query is so I can store the CompanyId and the CombinedValue data from pageId
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, (CAST(wp.pageId as varchar(200)) +'|'+ CAST(wp.productTypeId as varchar(200)) + '|' ) AS CombinedValue FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource connectionId = new SqlDataSource(DB_CONNECT, select);
connectionId.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)connectionId.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
string curCategoryProductTypeId = dView.Table.Rows[0]["CombinedValue"].ToString();
// EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId
// Lists All Categories #companyId has Active
string selectLoadData = "EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, selectLoadData);
conn.SelectParameters.Add("companyId", companyId);
lstCategoriesBox.Items.Clear();
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
// Pre-selects the value of the productTypeId you are trying to add a product for
// to send later run against a foreach insert in AddProduct()
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
testOutcomeCategory.InnerText = curCategoryProductTypeId;
lstCategoriesBox.DataSource = conn;
lstCategoriesBox.DataBind();
}
}
AddProduct:
private string AddProduct(string companyId, out string errMsg)
{
foreach (ListItem selectedItem in lstCategoriesBox.Items)
{
if (selectedItem.Selected)
{
// assign current productTypeId & pageId from selected Categories new CombinedValue column
string[] splitColumnValue = selectedItem.Value.Split('|');
string selectedPageId = splitColumnValue[0].ToString();
string selectedProductTypeId = splitColumnValue[1].ToString();
SqlDataSource connnection = new SqlDataSource(DB_CONNECT, "");
connnection.InsertCommand = "EXEC MCAdmin_AddProductFromClassic #pageId, #productTypeId, #productCode, #imgDirectory, #numSides, #sortOrder, #isActive, #template, #template2, #template3, #EditorJson, #MockupTemplateBase, #MockupTemplateTreatment, #BorderDefault ";
connnection.InsertParameters.Add("pageId", selectedPageId);
connnection.InsertParameters.Add("productTypeId", selectedProductTypeId);
connnection.InsertParameters.Add("productCode", txtProductCode.Text);
connnection.InsertParameters.Add("numSides", ddlNumSides.SelectedValue);
connnection.InsertParameters.Add("sortOrder", txtSortOrder.Text);
connnection.InsertParameters.Add("isActive", ddlActive.SelectedValue);
connnection.InsertParameters.Add("template", txtTemplate1.Text);
connnection.InsertParameters.Add("template2", txtTemplate2.Text);
connnection.InsertParameters.Add("template3", txtTemplate3.Text);
connnection.InsertParameters.Add("EditorJson", txtJson.Text);
connnection.InsertParameters.Add("MockupTemplateBase", txtMockupTemplateBase.Text);
connnection.InsertParameters.Add("MockupTemplateTreatment", txtMockupTemplateTreatment.Text);
connnection.InsertParameters.Add("BorderDefault", txtBorderDefault.Text);
/* Special Product Code for Upload Artwork Business Card */
if (txtProductCode.Text.ToUpper() == "BPFAH1-001-100")
{
connnection.InsertParameters.Add("imgDirectory", "/images/business-cards/general/");
}
else
{
connnection.InsertParameters.Add("imgDirectory", ddlImgDir.SelectedValue);
}
int result = connnection.Insert();
if (result > 0)
{
SqlDataSource connect = new SqlDataSource(DB_CONNECT, "");
connect.SelectCommand = "SELECT TOP 1 wtpProductId FROM WtpProducts ";
connect.SelectCommand = "WHERE productTypeId=#productTypeId AND pageId=#pageId DESC ";
connect.SelectParameters.Add("pageId", selectedPageId); //
connect.SelectParameters.Add("productTypeId", selectedProductTypeId); //
DataView dView = (DataView)connect.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string wtpProductId = dView.Table.Rows[0]["wtpProductId"].ToString();
errMsg = "";
return wtpProductId;
}
else
{
errMsg = "ERROR: Could not get productId of newly created Product.";
return "0";
}
}
else
{
errMsg = "ERROR: Could not add WtpProduct record to DB";
return "0";
}
}
else
{
errMsg = "ERROR: You must select a Category";
return "0";
}
}
errMsg = "ERROR: Did not make it into the foreach loop";
return "0";
}
OnClick method:
protected void OnClick_btnAddProduct(object sender, EventArgs e)
{
string pageId = Request.QueryString["pageid"];
testOutcomeCategory.InnerText = lstCategoriesBox.SelectedValue; // This proves that I have something selected!!!
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, baseImgDirectory, templateDirectory, wp.imageServer FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, select);
conn.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)conn.Select(DataSourceSelectArguments.Empty);
if(dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
if (!string.IsNullOrEmpty(pageId))
{
string errMsg;
string productId = AddProduct(companyId, out errMsg);
if(productId != "0")
{
Response.Redirect("/utilities/companydata/add-edit-wtp-product.aspx?productid=" + productId, true);
SetStatusMsg("Success", false);
}
else
{
SetStatusMsg(errMsg, true);
}
}
}
}
The list box instance is recreated on the server-side during the postback (as well as entire page). You do not set the selected items in the Page_Load event handler - if (!IsPostBack) goes to else branch. This is why you don't see them.
Ok,
lstCategoriesBox.Items.Clear();
Ok, above goes nuclear - blows out the list, blows out the selection.
Ok, that's fine
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
Ok, above adds a new item. Should be ok, but one should setup the lb BEFORE adding any data - including that "--select--" row.
It just makes sense to "setup" the lb and THEN start adding data, right?
However, But, if above works - ok, then lets keep going, but I would setup the lb before adding any rows of data. Say like this:
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
Now, the next line:
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
Ouch! - we just cleared the lb, and now we trying to set it to a value? You can't do that - the lb just been cleared, right? You would need to load up the lb first, and THEN you can set it to the selected value, right?
I might be missing something here, but that lb needs to be loaded up with valid data BEFORE you attempt to set the selected value?
To test first, change following
Outcome Category.InnerText = list CategoriesBox.SelectedValue;
to
Category.InnerText = Request.Form["CategoriesBox-ClientID"]
If the data is coming in correctly, the list view cleared or reloaded when between reload and click events the page.
UPDATE: I just figured it out! So stupid but when I check if(selectedItem.Selected) since I'm looping through the ListBox items it starts at the first index of the ListBox and since the first isn't selected then that if goes to the else block. Remove the else and it works fine
When my form is loaded, a query is run to get all employee records from SQL. Dapper compiles everything, and I put the contents in a List. My DataGridView table is bound to that list. I have a click event that retrieves the EmployeeID from the first column. Now, how do I sort through the List for the EmployeeModel with the matching ID without repeating the query? I will use this to bind other listboxes with the properties of that EmployeeModel. My first thought was to make the Form_Load method public and have it return employeeList, but it's an async method, and I don't know how to handle that. Would that be the right approach? Is the answer altogether different?
EDIT: I just noticed the first two lines are copied and pasted from my inventory initialization. They should read:
var employeeList = await InitializeEmployeeList();
EmployeeGridView.DataSource = employeeList;
public async void Dash_Load(object sender, System.EventArgs e)
{
var inventoryList = await InitializeInventoryList();
InventoryGridView.DataSource = inventoryList;
//Initialize Employee List
var employeeList = await InitializeEmployeeList();
EmployeeGridView.AutoGenerateColumns = false;
EmployeeGridView.ColumnCount=9;
EmployeeGridView.AutoSize = true;
EmployeeGridView.DataSource = employeeList;
EmployeeGridView.Columns[0].HeaderText = "Employee ID";
EmployeeGridView.Columns[0].DataPropertyName = "ID";
EmployeeGridView.Columns[1].HeaderText = "First Name";
EmployeeGridView.Columns[1].DataPropertyName = "FirstName";
EmployeeGridView.Columns[2].HeaderText = "Last Name";
EmployeeGridView.Columns[2].DataPropertyName = "LastName";
EmployeeGridView.Columns[3].HeaderText = "Nickname";
EmployeeGridView.Columns[3].DataPropertyName = "Nickname";
EmployeeGridView.Columns[4].HeaderText = "JobTitle";
EmployeeGridView.Columns[4].DataPropertyName = "JobTitle";
EmployeeGridView.Columns[5].HeaderText = "Forklift";
EmployeeGridView.Columns[5].DataPropertyName = "ForkliftCert";
EmployeeGridView.Columns[6].HeaderText = "AWP";
EmployeeGridView.Columns[6].DataPropertyName = "AWPCert";
EmployeeGridView.Columns[7].HeaderText = "Confined Space";
EmployeeGridView.Columns[7].DataPropertyName = "ConfinedSpaceCert";
EmployeeGridView.Columns[8].HeaderText = "NFPA51b";
EmployeeGridView.Columns[8].DataPropertyName = "NFPA51bCert";
}
{
DataGridViewCell selectedEmployeeCell = EmployeeGridView.CurrentCell;
int selectedEmployeeRow = selectedEmployeeCell.RowIndex;
string selectedEmployeeID = EmployeeGridView.Rows[selectedEmployeeRow].Cells[0].Value.ToString();
}
put a global
public static InvertoryList lst;
after getting data from your method
fill it with your data
if(lst==null)lst=new InvertoryList();
lst=your inventoryList;
then you can reach lst from everywhere in your form.
I have drop down and grid view..i fill drop down from database like this
There is two table tblReg and tblRes both have RegionID
protected void Page_Load(object sender, EventArgs e)
{
T1 tea = new T1();
var list1 = tea.tblReg.ToList();
var list = (from ta in list1
let data = ta.Region + " " + ta.StartDate ?? DateTime.Now.ToString() + " " + ta.EndDate ?? DateTime.Now.ToString()
select new { data, ta.RegionID }).ToList();
if(!Page.IsPostBack)
{
regiondrop.DataSource = list;
regiondrop.DataTextField = "data";
regiondrop.DataValueField = "RegionID";
regiondrop.DataBind();
}
}
now there is several values in drop down and i want when i select value from drop down then again to this value data will be display
On dropdown SelectedIndexChange i done this
protected void regiondrop_SelectedIndexChanged(object sender, EventArgs e)
{
T1 ts = new T1();
var dq=(from dropdwn in ts.tblRes
where dropdwn.RegionID==Convert.ToInt32(regiondrop.SelectedValue)
orderby dropdwn.OwnerName
select new {
FFID = dropdwn.FFID,
OwnerName = dropdwn.OwnerName,
RegNo = dropdwn.RegNo,
RegionID = dropdwn.RegionID,
});
GridView1.DataSource = dq;
GridView1.DataBind();
}
when i select value from dropdown it shows error
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.
on
GridView1.DataBind();
any solution
Well, as your error mentions, you can't do
Convert.ToInt32(regiondrop.SelectedValue)
in a linq to entities query (it can't be translated in sql / a store expression)
So just change these lines
var dq=(from dropdwn in ts.tblRes
where dropdwn.RegionID==Convert.ToInt32(regiondrop.SelectedValue)
to
var selectedValue = Convert.ToInt32(regiondrop.SelectedValue);
var dq=(from dropdwn in ts.tblRes
where dropdwn.RegionID==selectedValue
You could also do (but the previous solution is more readable)
var dq=(from dropdwn in ts.tblRes
where SqlFunctions.StringConvert((double)dropdwn.RegionID)==regiondrop.SelectedValue
There's a method in SqlFunctions to convert a numeric to a string, but... not a string to a numeric value.
I have a text box which I manage its text changing event to filter the RadGrid:
private void txtJob_TextChanging(object sender, TextChangingEventArgs e)
{
this.gridCustomers.Columns["JobColumn"].FilterDescriptor = new FilterDescriptor
{
Operator = FilterOperator.Contains,
Value = txtJob.Text
};
}
I change JobColumn Text using CellFormatting Event:
private void gridCustomers_CellFormatting(object sender, CellFormattingEventArgs e)
{
if (e.Column.Name == "JobColumn")
e.CellElement.Text = db.tblJobs.First(x => x.JobID == Convert.ToInt32(e.Row.Cells[9].Value.ToString())).JobName;
}
I'm replacing Job ID with its Job Name in JobColumn, in that Text Box which I filtering RadGrid I'm searching for Job Name which is visible in RadGrid Now, but it will filter based on Job ID which is the default value before replacing.
So How can I filter a RadGrid Column based on its Text not Value?
For more information I'm binding a table like this to my girdview:
int JobID
nvarchar(10) Name
nvarchar(100) Address
.
.
.
And I have a table named Jobs like this:
int JobID
nvarchar(30) JobName
.
.
.
I need to get JobID from table one and in data binding (cell Formatting) replace the ID with its JobName in Jobs table.
Why I'm not selecting new and joining two table? because in that case I have not a grid view which can be edited easily, I must use Virtual Gird which is not my goal.
You are trying to hack the system. The correct approach in your case is to use GridVieWComboBoxColumn, which can be bound and DisplayMember and ValueMember to be specified. It also has FilterMode property to determine which field to use for filtering.
Read more GridViewComboBoxColumn | Telerik UI for WinForms Documentation
UPDATE
Here is a sample to get you started
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
DataTable mainTable = new DataTable();
mainTable.Columns.Add("JobID", typeof(int));
mainTable.Columns.Add("Name");
mainTable.Columns.Add("Address");
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
mainTable.Rows.Add(rand.Next(1,4), "Name " + i, "Address " + i);
}
DataTable jobsTable = new DataTable();
jobsTable.Columns.Add("JobID", typeof(int));
jobsTable.Columns.Add("JobName");
jobsTable.Rows.Add(1, "ABC ");
jobsTable.Rows.Add(2, "DFG");
jobsTable.Rows.Add(3, "XCV");
radGridView1 = new RadGridView() { Dock = DockStyle.Fill, AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill };
this.Controls.Add(radGridView1);
radGridView1.EnableFiltering = true;
radGridView1.DataSource = mainTable; //this will create all columns
radGridView1.Columns.Remove(radGridView1.Columns["JobId"]);
GridViewComboBoxColumn comboCol = new GridViewComboBoxColumn();
comboCol.DataSource = jobsTable;
comboCol.FieldName = "JobID"; //the name of the field in the main table to look for
comboCol.DisplayMember = "JobName"; //you want to see job names not ids
comboCol.ValueMember = "JobID";
comboCol.FilteringMode = GridViewFilteringMode.DisplayMember;
radGridView1.Columns.Insert(0, comboCol);
}
private void radButton1_Click(object sender, EventArgs e)
{
radGridView1.Columns["JobID"].FilterDescriptor = new FilterDescriptor
{
Operator = FilterOperator.Contains,
Value = "B"
};
}
I'm trying to accomplish the following and would appreciate any help.
I have a CSV file containing 2 columns, 1 a list of names and the other a list of associated IDs.
Eg.
Test1, 00001
Test2, 00002
I have read these into my program into 2 lists.
1. nameList
2. idList
I have populated the datasource of a combobox with the values of nameList.
Now, when a name is selected in the combobox and a button pressed, I would like to get the ID. So if Test1 is selected, when the button is pressed 00001 is returned where as if Test2 is selected and the button pressed, 00002 is returned.
If it helps at all, this is what im currently using to populate the Lists.
public void nameCSV()
{
var reader = new StreamReader(File.OpenRead(#"C:\temp\nameList.csv"));
List<string> nameList = new List<string>();
List<string> idList = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
nameList.Add(values[0]);
idList.Add(values[1]);
}
cmbxName.DataSource = releaseNameList;
}
public void nameCSV()
{
var reader = new StreamReader(File.OpenRead(#"C:\temp\nameList.csv"));
DataTable tbl = new DataTable();
tbl.Columns.Add("Name", typeof(string));
tbl.Columns.Add("ID", typeof(string));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
DataRow row = tbl.NewRow();
row["Name"]=values[0];
row["ID"] = values[1];
tbl.Rows.Add(row);
}
cmbxName.DisplayMember = "Name";
cmbxName.ValueMember = "ID";
cmbxName.DataSource = tbl;
}
You need something like that. Check properties DisplayMember and ValueMember of ComboBox.
So when the button is clicked and you want to take the Value not the display text.
protected void Button1_Click(object sender, EventArgs e)
{
string id = cmbxName.SelectedValue;
}
N.B: Your title is misleading !
Use a Dictionary
public void nameCSV()
{
var reader = new StreamReader(File.OpenRead(#"C:\temp\nameList.csv"));
Dictionary<string, int> userDict = new Dictionary<string, int>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
userDict.Add(values[0], values[1]);
}
cmbxName.DataSource = userDict;
}
to call the value of a given user id just use the key. For example, 'Test1'
string Username = "Test1";
int userid;
userid = userDict[Username];
One note, dictionaries work better with numeric values as the key, not strings. Put in your case you're looking up the string name, so it should be this way. As long as the string lengths are short - aka no more than 10 characters. Peformance wise, you should be okay.