I searched similar questions but none of them applyed to my situation.
So i have a listbox witch is supposed to fill with data depending on a selected item from a combobox.
The code worked fine but because of some changes made in the software i had to create a new form, copy/paste the design and the code to the new form.
I made the necessary adjustments but now, all the comboboxes fill and the listbox wont.
Can anyoe say why, the code is:
using System;
using System.Data;
using System.Windows.Forms;
using XXXXX.bin;
using System.Data.SqlClient;
using System.IO;
using System.Drawing.Imaging;
using System.Linq;
namespace XXXXX
{
public partial class vidro : Form
{
public static SqlConnection con = Globais.GetDbConection();
public vidro()
{
InitializeComponent();
}
private void vidro_Load(object sender, EventArgs e)
{
SqlDataAdapter SDA = new SqlDataAdapter("select distinct desempenho from vidros", con);
DataTable DTT = new DataTable();
SDA.Fill(DTT);
desempenho.Items.Clear();
foreach (DataRow ROW in DTT.Rows)
{
desempenho.Items.Add(ROW["desempenho"].ToString());
}
SqlDataAdapter SDA2 = new SqlDataAdapter("select distinct valu from vidros", con);
DataTable DTT2 = new DataTable();
SDA2.Fill(DTT2);
valu.Items.Clear();
foreach (DataRow ROW in DTT2.Rows)
{
valu.Items.Add(ROW["valu"].ToString());
}
SqlDataAdapter SDA3 = new SqlDataAdapter("select distinct fs from vidros", con);
DataTable DTT3 = new DataTable();
SDA3.Fill(DTT3);
fsolar.Items.Clear();
foreach (DataRow ROW in DTT3.Rows)
{
fsolar.Items.Add(ROW["fs"].ToString());
}
SqlDataAdapter SDA4 = new SqlDataAdapter("select distinct sel from vidros", con);
DataTable DTT4 = new DataTable();
SDA4.Fill(DTT4);
select.Items.Clear();
foreach (DataRow ROW in DTT4.Rows)
{
select.Items.Add(ROW["sel"].ToString());
}
SqlDataAdapter SDA5 = new SqlDataAdapter("select distinct compo from vidros", con);
DataTable DTT5 = new DataTable();
SDA5.Fill(DTT5);
select.Items.Clear();
foreach (DataRow ROW in DTT5.Rows)
{
compo.Items.Add(ROW["compo"].ToString());
}
SqlDataAdapter SDA6 = new SqlDataAdapter("select distinct sel from vidros", con);
DataTable DTT6 = new DataTable();
SDA6.Fill(DTT6);
select.Items.Clear();
foreach (DataRow ROW in DTT6.Rows)
{
select.Items.Add(ROW["sel"].ToString());
}
}
private void desempenho_SelectedIndexChanged(object sender, EventArgs e)
{
FillData();
}
private void valu_SelectedIndexChanged(object sender, EventArgs e)
{
FillData();
}
private void fsolar_SelectedIndexChanged(object sender, EventArgs e)
{
FillData();
}
private void selec_SelectedIndexChanged(object sender, EventArgs e)
{
FillData();
}
private void compo_SelectedIndexChanged(object sender, EventArgs e)
{
FillData();
}
private void FillData()
{
string combo1value = desempenho.Text;
string combo2value = valu.Text;
string combo3value = fsolar.Text;
string combo4value = select.Text;
string combo5value = compo.Text;
string query = "select [desc],[enchimento],[compo] from vidros where 1=1 ";
string queryWhere = "";
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
sda.SelectCommand = cmd;
if (combo1value != "")
{
queryWhere += " and desempenho = #emp ";
sda.SelectCommand.Parameters.Add("#emp", SqlDbType.NVarChar).Value = combo1value;
}
if (combo2value != "")
{
queryWhere += " and valu = #emp2 ";
sda.SelectCommand.Parameters.Add("#emp2", SqlDbType.NVarChar).Value = combo2value;
}
if (combo3value != "")
{
queryWhere += " and fs = #emp3 ";
sda.SelectCommand.Parameters.Add("#emp3", SqlDbType.NVarChar).Value = combo3value;
}
if (combo4value != "")
{
queryWhere += " and sel = #emp4 ";
sda.SelectCommand.Parameters.Add("#emp4", SqlDbType.NVarChar).Value = combo4value;
}
if (combo5value != "")
{
queryWhere += " and compo = #emp5 ";
sda.SelectCommand.Parameters.Add("#emp5", SqlDbType.NVarChar).Value = combo5value;
}
sda.SelectCommand.CommandText = query + queryWhere;
DataTable DTT = new DataTable();
sda.Fill(DTT);
listView1.Items.Clear();
for (int i = 0; i < DTT.Rows.Count; i++)
{
DataRow dr = DTT.Rows[i];
ListViewItem listitem = new ListViewItem(dr["desc"].ToString());
listitem.SubItems.Add(dr["enchimento"].ToString());
listitem.SubItems.Add(dr["compo"].ToString());
listView1.Items.Add(listitem);
}
}
Because you transferred the code to a new form you will need to hook up your event handlers for the controls.
This can be done in the designer by selecting a control and going to its event tab (the lightning shape near properties)
Or in code by doing: controlName.EventName += eventHandlerMethodName;
Example: button1.Click += button1_Click;
Make sure that the control names(ComboBox and Listbox) are the same as in the copied code and add eventlisteners for each control after that.
Related
I am new to c# and trying to search a listbox as following :
First i have this :
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlCommand cmd;
SqlDataReader DataRead;
...
public FrmCodes()
{
InitializeComponent();
cmd = new SqlCommand("Select Item from Items", Cn);
Cn.Open();
DataRead = cmd.ExecuteReader();
while (DataRead.Read())
{
ListItems.Items.Add(DataRead["Item"].ToString());
}
DataRead.Close();
Cn.Close();
}
And tried to do this :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
while (DataRead.Read())
{
string str = DataRead["Item"].ToString();
string srch = txtSrch.Text;
if (str.Contains(srch))
{
ListItems.Items.Add(str);
}
}
}
It did not work , I tried to make a new sql select query that get data depending on txtSrch.Text but got nothing either .
Thanks in advance.
Edit#1
This is the query i mentioned before :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}
This did not affect the items in the listbox nothing happens on txtSrch Change .
Another solution using Dataview thanks to #Trevor
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlDataAdapter da;
DataTable dt = new DataTable();
...
public FrmCodes()
{
InitializeComponent();
da = new SqlDataAdapter("Select Item from Items", Cn);
da.Fill(dt);
DataView dv = new DataView(dt);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Textbox change :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
DataView dv = new DataView(dt);
string srch = txtSrch.Text;
dv.RowFilter = string.Format("Item Like '%{0}%'", srch);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Thanks.
Basedon #Olivier Jacot-Descombes’ comments, this worked for me:
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}
I want to filter listbox data by using datagridview cell instead of using textbox.I am using the following code.
private void searchLedger(string value)
{
cn.Open();
SqlCommand cmd = new SqlCommand("Select * from LedgerCreation Where ledgerName like #LedgerName and AddClassification = #AddClassification order by LedgerName", cn);
cmd.Parameters.AddWithValue("#AddClassification", "Cash/Bank");
cmd.Parameters.AddWithValue("#LedgerName", "%" + value + "%");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
da.Fill(table);
LstReceipt.DataSource = table;
LstReceipt.DisplayMember = "LedgerName";
cn.Close();
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 1)
{
searchLedger(dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString());
}
}
i have this code that create Master-Detail XtraGrid at runtime
public partial class FRM_Reserved : DevExpress.XtraEditors.XtraForm
{
DataTable Table1 = new DataTable("Table1");
DataTable Table2 = new DataTable("Table2");
DataSet dataSet = new DataSet();
public FRM_Reserved()
{
InitializeComponent();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables["Table1"].Columns["Bon N"],
dataSet.Tables["Table2"].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables["Table1"];
}
I want to refreshing DataSource on a click of button so I added this code
private void btnRefresh_Click(object sender, EventArgs e)
{
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
but the code does not work ,can you help me please.
Try below code. Hope it works
private void btnRefresh_Click(object sender, EventArgs e)
{
gridControl3.DataSource=null;
gridControl3.Items.Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
the problem was in the name of the tables it change every time
dataSet.Tables[(Table1.TableName)]
dataSet.Tables[(Table2.TableName)]
so I made this changes
private void simpleButton1_Click(object sender, EventArgs e)
{
dataSet.Relations.Clear();
dataSet.Tables["Table2"].Clear();
dataSet.Tables["Table1"].Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables[(Table1.TableName)].Columns["Bon N"],
dataSet.Tables[(Table2.TableName)].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables[(Table1.TableName)];
gridControl3.ForceInitialize();
}
Thanks for helping me
Use the following code
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.RefreshDataSource();
Try this one
private void button1_Click(object sender, EventArgs e)
{
var ds = new DataSet();
var dt1 = GetTable1Data();
var dt2 = GetTable2Data();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
ds.Relations.Add("RelationTable",
ds.Tables["Table1"].Columns["col1"],
ds.Tables["Table2"].Columns["col1"]);
gridControl1.DataSource = ds.Tables["Table1"];
gridControl1.RefreshDataSource();
}
private DataTable GetTable1Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
using (var cmd = new SqlCommand("Stored procedure name goes here", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
private DataTable GetTable2Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
const string sql = "SELECT * FROM Table2";
using (var cmd = new SqlCommand(sql, conn))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
Both of these functions are working fine, one should fill up datagrid with data, the other, should be triggered when i select a row from the first datagrid. But for some reason the second function is causing datagrid to fill just one row of data.
private void fillDataGrid(DataGridView dg, string query) {
OracleCommand cmd = new OracleCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
OracleDataAdapter oda = new OracleDataAdapter(cmd);
DataTable dt = new DataTable();
try {
cmd.ExecuteNonQuery();
oda.Fill(dt);
**dg.DataSource = dt;**
}
catch(Exception e) {
MessageBox.Show(e.ToString());
}
}
This function is called when i load the form, and it is working fine on its own. But when the next function is causing some kind of problem and i don't know why.
private void dataGridView1_SelectionChanged_1(object sender, EventArgs e)
{
String s = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
String upit = "select dn.* from detaljinarudzbe dn, narudzba n where dn.nid = n.nid and n.jmbg = " + s + "";
fillDataGrid(dataGridView2, upit);
}
It is working fine, but i get just one row in first datagridview. And expection says
system.argument out of range exception:must be non negative and less
than the size of collection
Caused by the ** line in first method. I don't get why is the event causing this problem. when i use the second function on a button it is working fine.
You can try (I using SQL Server) : attention check SelectedRows[0] by SelectedRows.Count
private void fillDataGrid(DataGridView dg, string query) {
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlDataAdapter oda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try {
conn.Open();
cmd.ExecuteNonQuery();
oda.Fill(dt);
conn.Close();
dg.DataSource = dt;
}
catch(Exception e) {
MessageBox.Show(e.ToString());
}
finally
{
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if(dataGridView1.SelectedRows.Count > 0)
{
String s = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
String upit = "Select * from CARD_NO where CT_ID = " + s + "";
fillDataGrid(dataGridView2, upit);
}
}
private void Form1_Load(object sender, EventArgs e)
{
fillDataGrid(dataGridView1, "Select * from CARD_TYPE");
}
Here is my code to load the rbl:
protected void rblContentTypesGetAll_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(Global.conString))
{
using (SqlCommand cmd = new SqlCommand("contentTypeGetAll", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
//Clear Items before reloading
rblContentTypesGetAll.Items.Clear();
//Populate Radio button list
for (int i = 0; i < dt.Rows.Count; i++)
{
rblContentTypesGetAll.Items.Add(new ListItem(dt.Rows[i]["contentType"].ToString() + " - " + dt.Rows[i]["description"].ToString(),
dt.Rows[i]["ID"].ToString()));
}
//Set Default Selected Item by Value
rblContentTypesGetAll.SelectedIndex = rblContentTypesGetAll.Items.IndexOf(rblContentTypesGetAll.Items.FindByValue(((siteParams)Session["myParams"]).DefaultContentType.ToLower()));
}
Here is the HTML:
<asp:RadioButtonList id="rblContentTypesGetAll" OnLoad="rblContentTypesGetAll_Load" runat="server">
</asp:RadioButtonList>
Here is the form taking the submission:
protected void Submit_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(Global.conString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("contentPageInsert", con))
{
cmd.Parameters.Add("#title", SqlDbType.VarChar).Value = Global.SafeSqlLiteral(txtPage.Text, 1);
cmd.Parameters.Add("#contentTypeID", SqlDbType.VarChar).Value = rblContentTypesGetAll.SelectedValue;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
con.Close();
//Update Content Page Repeater
using (SqlCommand cmd = new SqlCommand("contentPageGetAll", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
Session["formProcessed"] = "Page added!";
Response.Redirect(redirectURL);
}
No matter which radio button I select, the value is always the same - first radio button. What am I doing incorrectly?
The reason, I think, is that the method that is populating radio button list clears and rebuilds on every postback so the by the time submit_click fires, the list has been rebuilt and the selection is lost. Try this,
protected void rblContentTypesGetAll_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
return;
}
var dt = new DataTable();
using (var con = new SqlConnection(Global.conString))
using (var cmd = new SqlCommand("contentTypeGetAll", con))
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
//Clear Items before reloading
rblContentTypesGetAll.Items.Clear();
//Populate Radio button list
for (int i = 0; i < dt.Rows.Count; i++)
{
rblContentTypesGetAll.Items.Add(new ListItem(dt.Rows[i]["contentType"].ToString() + " - " + dt.Rows[i]["description"].ToString(),
dt.Rows[i]["ID"].ToString()));
}
//Set Default Selected Item by Value
rblContentTypesGetAll.SelectedIndex = rblContentTypesGetAll.Items.IndexOf(rblContentTypesGetAll.Items.FindByValue(((siteParams)Session["myParams"]).DefaultContentType.ToLower()));
}