I have a listbox in my webform from which I am trying to select multiple values, but I am only getting last selected values. I have tried in two ways. First I explicitly added list items:
<asp:ListBox ID="ListBox2" runat="server"
SelectionMode="Multiple" AutoPostBack="True">
<asp:ListItem>teama</asp:ListItem>
<asp:ListItem>teamb</asp:ListItem>
</asp:ListBox>
Second, I tried to bind to a table in a database:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListBox2.SelectionMode = ListSelectionMode.Multiple;
string scon = ConfigurationManager.ConnectionStrings["Test_AthiraConnectionString"].ConnectionString;
SqlConnection con=new SqlConnection(scon);
con.Open();
SqlCommand cmd = new SqlCommand("select department from department", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ListBox2.DataSource = ds;
ListBox2.DataValueField = "department";
ListBox2.DataTextField = "department";
ListBox2.DataBind();
con.Close();
}
}
Then I tried these different methods to select multiple items on buttonclick event
First:
string k =null ,k1 = null;
foreach (int i in ListBox2.GetSelectedIndices())
{
k1 = ListBox2.Items[i].Text + "/";
k += k1;
Response.Write(k);
}
Second:
foreach (ListItem li in ListBox2.Items)
{
if (li.Selected == true)
{
k += li.Text + "/";
Response.Write(k);
}
}
Third:
k = String.Join("/", ListBox2.Items
.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i=>i.Value)
.ToArray());
Response.Write(k);
Fourth:
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
{
if (ListBox2.Items[i].Selected == true)
{
k1 = ListBox2.Items[i].Text + "/";
k += k1;
Response.Write(k);
}
}
But none of them seem to work. I am getting only the last selected value.
You may access the items in the list as follow and check their properties.
IEnumerator ie = ListBox2.Items.GetEnumerator();
while (ie.MoveNext())
{
ListItem li = (ListItem)ie.Current;
//Use ListItem here
}
please try below code, It will return coma separator string for Listbox selected value
public string GetSelectedValues()
{
string selectedVal = string.Empty;
int i = 0;
foreach (int index in lstbox.GetSelectedIndices())
{
if (i == 0)
selectedVal = lstbox.Items[index].Value;
else
selectedVal = selectedVal + ";" + lstbox.Items[index].Value.ToString();
i++;
}
return selectedVal ;
}
Related
How to Add key press in ' if(count<= 3)' condition. in this code we have define that if the input length is less than 3 or equal to 3 consider the input as quantity and then again go for the input if the input length is greater than 3 then consider the input as item code and search from database and quantity that we have entered it first time.
enter code here
private void SearchItem_KeyPress(object sender, KeyPressEventArgs e){
if (e.KeyChar == (char)Keys.Enter){
ItemLength = SearchItem.Text;
int count = 0;
for (int i = 0; i < ItemLength.Length; i++)
{
count++;
}
else if (count <= 3)
{
string qtyvalue = ItemLength;
SearchItem.Text = "1001";
SearchItem.Focus();
GetItemCode();
SearchItem.Text = Itemcodes;
//if (count <= 3 )
//{
SqlConnection conn = new SqlConnection(myconstring);
string query = "SELECT ItemCode, ItemDescription, SRate FROM ITEM WHERE ItemCode
= #ItemCode ";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#ItemCode", SearchItem.Text);
//cmd.Parameters.AddWithValue("#ItemDescription", SearchItem.Text);
conn.Open();
// DataTable dt = new DataTable(query);
SqlDataReader dr = cmd.ExecuteReader();
// da.Fill(dr);
if (dr.Read())
{
bool Found = false;
if (SaleItemList.Rows.Count > 0)
{
foreach (DataGridViewRow drrr in SaleItemList.Rows)
{
if (Convert.ToString(drrr.Cells[0].Value) == SearchItem.Text && drrr.Cells[1].Value == drr["ItemDescription"])
{
drrr.Cells[2].Value = Convert.ToString(Convert.ToInt16(qtyvalue) + Convert.ToInt16(drrr.Cells[2].Value));
drrr.Cells[4].Value = Convert.ToString(Convert.ToInt16(drrr.Cells[2].Value) * Convert.ToDouble(drrr.Cells[3].Value));
Found = true;
TotalAmount.Text = (from DataGridViewRow row in SaleItemList.Rows
where row.Cells[4].FormattedValue.ToString() != string.Empty
select Convert.ToInt32(row.Cells[4].FormattedValue)).Sum().ToString();
Clear();
}
}
if (!Found)
{
drr = dt.NewRow();
drr["ItemCode"] = dr.GetValue(0).ToString();
drr["ItemDescription"] = dr.GetValue(1).ToString();
drr["Qty"] = ItemLength;
drr["Rate"] = dr.GetValue(2).ToString();
drr["Amount"] = Convert.ToInt32(drr["Qty"]) * Convert.ToDouble(drr["Rate"]);
dt.Rows.Add(drr);
SaleItemList.DataSource = dt;
TotalAmount.Text = (from DataGridViewRow row in SaleItemList.Rows
where row.Cells[4].FormattedValue.ToString() != string.Empty
select Convert.ToInt32(row.Cells[4].FormattedValue)).Sum().ToString();
Clear();
SearchItem.Focus();
}
}
else
{
drr = dt.NewRow();
drr["ItemCode"] = dr.GetValue(0).ToString();
drr["ItemDescription"] = dr.GetValue(1).ToString();
drr["Qty"] = ItemLength;
drr["Rate"] = dr.GetValue(2).ToString();
drr["Amount"] = Convert.ToInt32(drr["Qty"]) * Convert.ToDouble(drr["Rate"]);
dt.Rows.Add(drr);
SaleItemList.DataSource = dt;
TotalAmount.Text = (from DataGridViewRow row in SaleItemList.Rows
where row.Cells[4].FormattedValue.ToString() !=
string.Empty
select Convert.ToInt32(row.Cells[4].FormattedValue)).Sum().ToString();
Clear();
SearchItem.Focus();
}
}
}
}
enter code here
I have 3 listboxes.The listbox fetches two values by code-datatextfield and datavaluefield. 1st listbox transfers the datatextfield items from 1st listbox to 2nd listbox.i want to transfer the datavaluefield of selected 1st listbox items to 3rd listbox.
if (ListBox3.SelectedIndex >= 0
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
Session["value"] = ListBox3.Items[i];
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}
for listbox 3
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where pname='" + this.DropDownList1.SelectedValue + "'" ,con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox3.DataSource = ds.Tables[0];
ListBox3.DataTextField = "paramtext";
ListBox3.DataValueField = "param";
ListBox3.DataBind();
}
}
But i want to display the datavaluefield of the items that are selected from listbox3 to listbox1
Since you want to show DataTextField value and DataValueField value from one listbox into 2 different listbox. I suggest you to use a different approach. This will also reduce usage of 2nd database call.
Try following:-
if (ListBox3.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
//Session["value"] = ListBox3.Items[i]; no need of this
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (ListBox2.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
//since you already have text and value field values in arrayList. Use them
ListBox2.Items.Add(new ListItem(((ListItem)arraylist1[i]).Text));
}
if (ListBox1.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
ListBox1.Items.Add(new ListItem((ListItem)arraylist1[i]).Value));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
/* This database call can be removed
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}*/
I have a checkboxlist i have inserted selected item to database.now having problem
to return those item to checkbox and make other item unselected.
My chekboxlist is given below.
<asp:CheckBoxList ID="Chk_type" runat="server" RepeatDirection="Horizontal"
CellPadding="2" CellSpacing="2" RepeatColumns="3" TextAlign="Right">
<asp:ListItem>KG School(Bangla Medium)</asp:ListItem>
<asp:ListItem>KG School(English Medium)</asp:ListItem>
<asp:ListItem>Vocational Institute</asp:ListItem>
<asp:ListItem>Secondary School</asp:ListItem>
<asp:ListItem>Degree College(With HSC)</asp:ListItem>
<asp:ListItem>Honors College(With HSC)</asp:ListItem>
<asp:ListItem>Honors College(Without HSC)</asp:ListItem>
<asp:ListItem>University College</asp:ListItem>
<asp:ListItem>University</asp:ListItem>
<asp:ListItem>Polytechnic Institute</asp:ListItem>
<asp:ListItem>Coaching Center</asp:ListItem>
</asp:CheckBoxList>
Code behind to insert selected item to database is
String str = "";
for (int i = 0; i <= Chk_type.Items.Count - 1; i++)
{
if (Chk_type.Items[i].Selected)
{
if (str == "")
{
string sql = #"INSERT INTO institute_type (inst_code,inst_type) VALUES ('" + Txtnst_code.Text + "','" + Chk_type.Items[i].Text + "')";
Connstring.insert(sql);
}
else
{
// str += Chk_type.Items[i].Text;
}
}
}
Response.Write("Your data Sucessfully saved");
Chk_type.SelectedIndex = -1;
now i want return item will be selected and other will be unselected
to get return item i am using this function
public void bind_checkbox()
{
DataTable dt = Connstring.SqlDataTable(#"select version FROM institute_info WHERE inst_code = '" + Txtnst_code.Text + "'");
Check_version.DataSource = dt;
Check_version.DataTextField = "version";
Check_version.DataValueField = "inst_code";
Check_version.DataBind();
}
database table structure is
Solution is
private void bind_checkbox_inst_type()
{
string qur = #"SELECT inst_type FROM institute_type";
DataTable dt =Connstring. SqlDataTable(qur);
if (dt.Rows.Count > 0)
{
for (int i = 0; i <= Chk_type.Items.Count - 1; i++)
{
foreach (DataRow dr in dt.Rows)
{
if (Chk_type.Items[i].Text == dr["inst_type"].ToString().Trim())
{
Chk_type.Items[i].Selected=true ;
break;
}
}
}
}
}
I have one repeater which displays the list of puja.i have also used one datalist to display the names of temples.whenever i click on search it displays only the last value of the repeater i.e it is taking only the last value of the repeater....my question is how to use loop inside a repeater???
here is my code behind how i used datalist and repeater:
protected void Page_Load(object sender, EventArgs e)
{
//lblnodatafound.Visible = true;
//lbldatafound.Visible = false;
if (Request.QueryString["search"] != null)
{
var dt = new DataTable("Data");
String source = Request.QueryString["search"];
var splitseparator = new string[] { " " };
String[] result = source.Split(splitseparator, StringSplitOptions.RemoveEmptyEntries);
foreach (String s in result)
{
if (IsAlphaNumeric(s) == true)
{
var dttemp = new DataTable();
dttemp = fnsearch(s);
dt.Merge(dttemp, true);
}
}
if (dt.Rows.Count != 0)
{
int count = dt.Rows.Count;
if (dt.Rows.Count > 0)
{
DataList1.DataSource = dt;
DataList1.DataBind();
lblnodatafound.Visible = false;
lbldatafound.Visible = true;
//added the repeater to display the list of puja
for (int i = 0; i < dt.Rows.Count; i++)
{
String id = dt.Rows[i]["id"].ToString();
string query = "select puja.id,puja.name as puja_name, mandir.name as mandir_name from puja,mandir where mandir.id= puja.with_mandir and puja.with_mandir = '" + id + "'";
conn.Open();
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataTable dt1 = new DataTable();
adp.Fill(dt1);
conn.Close();
if (dt1.Rows.Count > 0)
{
lblmandirpuja.Text = "Poja in " + dt1.Rows[0]["mandir_name"];
foreach (RepeaterItem repeatItem in Repeater1.Items){
Repeater1.DataSource = dt1;
Repeater1.DataBind();
}
}
}
}
}
else
{
lblnodatafound.Visible = true;
lbldatafound.Visible=false;
}
}
}
Try to change this line:
if (dt1.Rows.Count > 0)
for something like:
for(int i = 0; i < dt1.Rows.Count; i++)
And this one:
lblmandirpuja.Text = "Poja in " + dt1.Rows[0]["mandir_name"];
The 0 for the i:
lblmandirpuja.Text = "Poja in " + dt1.Rows[i]["mandir_name"];
I need to check if a cell is empty and store a message to then create a new cell in every row that contains all the messages
But I don't know know how to work with DevExpress can someone help with my code
string Name = "First Name";
string FName = "Father Name";
string LName = "Last Name";
string EmpCode = "Employee Code";
string Tax = "Tax#";
string SocSec = "Soc.Sec#";
string EmpType = "Employment Type";
string DepCode = "Department Code";
string DepDesc = "Department Description";
private void simpleButton1_Click(object sender, System.EventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=C:\\Users\\pc\\Documents\\Emp.xlsx;Extended Properties=\"Excel 12.0;HDR=Yes\"";
con.Open();
DataTable dtSchema;
dtSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
OleDbCommand Command = new OleDbCommand ("select * FROM [" + dtSchema.Rows[0]["TABLE_NAME"].ToString() + "]", con);
OleDbDataAdapter da = new OleDbDataAdapter(Command);
DataSet ds = new DataSet ();
da.Fill(ds);
dataGrid1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
This loop isn't giving me the right message about empty cells I think it's not right what i wrote maybe there's another better way...
for (int rows = 0 ; rows < gridView3.RowCount ; rows ++)
{
string[] msg = new string[50];
if ((gridView3.GetRowCellValue(rows, gridView3.Columns["LName"])) == null)
{
msg[rows] = "name missing";
}
}
From what I know the cell's value won't be null. The underlying datasource however will have a null value.
To check if a cell's data is null or summed from nulls:
private bool IsNullValue(PivotDrillDownDataSource ds, PivotGridField field)
{
if (ds.RowCount == 0 || field == null) return false;
for (int i = 0; i < ds.RowCount; i++)
{
if (Equals(ds[i][field], null))
return true;
}
return false;
}
To change text in null cell:
if (IsNullValue(e.CreateDrillDownDataSource(), e.DataField))
e.DisplayText = "NULL OR SUM WITH NULL";
I had the same issue and below code worked fine for me, just slightly changed from this what OP tried. I hope it will help somebody.
for (int rows = 0 ; rows < gridView3.RowCount ; rows ++)
{
string[] msg = new string[50];
if ((gridView3.GetRowCellValue(rows, "LName")) == null)
{
msg[rows] = "name missing";
}
}
LName need to replaced by string fieldName.
private void gridViewPro_RowStyle(object sender,
DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{
GridView View = sender as GridView;
if (e.RowHandle >= 0)
{
double Sale = Convert.ToDouble(
View.GetRowCellDisplayText(e.RowHandle, View.Columns["PRO_S3M"]));
double Qua = Convert.ToDouble(
View.GetRowCellDisplayText(e.RowHandle, View.Columns["PRO_QTY"]));
if (Sale > 0 && Qua > 0)
{
if (Sale >= Qua)
{
e.Appearance.BackColor = Color.OrangeRed;
}
}
}
}
Use This Event Of AspxGridView
protected void grid_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
{ // Get Cell Values here and compare as per your conditions
string text = e.CellValue.ToString();
}