I have a textbox and a listbox in my c# forms application. What I want to do is that the user will enter the query in the textbox and I want to display the portion of that query into my listbox.
For example:
Here, I want to display "att1" and "att2" in my listbox named "Query Options"(i.e. listBox1). How can I do that?
This is the code I have written until now:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string x = (sender as Control).Text;
listBox1.BeginUpdate();
try
{
XmlDocument xdata = new XmlDocument();
xdata.Load("C:\\Ankush\\Visual Studio Project\\Query Info.xml");
XmlNodeList qlist = xdata.SelectNodes("information/QueryInfo/Query");
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (listBox1.Items[i].ToString().ToLower().Contains(textBox1.Text.ToLower()))
listBox1.SetSelected(i, true);
foreach (XmlNode node in qlist)
{
listBox1.DataSource = xdata;
listBox1.Items.Add(node.InnerText);
}
}
//listBox1.DataSource = xdata;
string cmdstr = #"select * from information_schema.columns where table_name = '" + comboBox1.SelectedItem + "'";
string conStr = #"Data Source=INPDDBA027\NGEP;Initial Catalog=Dev_Server;Integrated Security=True";
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmdstr, conStr);
sda.Fill(dt);
listBox2.DataSource = dt;
listBox2.DisplayMember = "Column_Name";
}
finally
{
listBox1.EndUpdate();
}
}
Please Help.
Related
I am writing a project in ASP.net which I have six text boxes to display the information of the next record in my database. And I also have a search button base on some selected field which will search out my first record in my database. I inserted the code for my first record into the search button event handler. The code is written below:
Using System.Data;
Using System.Data.OleDb;
Using System.IO;
OleDbconnection mycon = new OleDbconnection("");
protected void search_btn_Click(object sender, EventArgs e)
{
int i = 0;
DataTable dt;
String searchme = "select * from student where myclass = '" + txtclass.Text + "' and mytype = '" + txtclasstype.Text + "'";
OleDbCommand cmd = new OleDbCommand (searchme, mycon);
mycon.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
if(dt.Rows.Count > 0)
{
i = 0;
txtsearbox.Text = dt.Rows[i]["Admin_no"].ToString();
txtsurname.Text = dt.Rows[i]["surname"].ToString();
txtfirstname.Text = dt.Rows[i]["firstname"].ToString();
txtothername.Text = dt.Rows[i]["othername"].ToString();
txtsex.Text = dt.Rows[i]["sex"].ToString();
Photo.ImageUrl = dt.Rows[i]["photo"].ToString();
// then I created a session to hold my dt.
Session["dt"] = dt;
}
mycon.Close();
}
The above code is working fine for my first record but where I am having problem is from my next button which is written as shown below:
protected void next_btn_Click(object sender, EventArgs e)
{
int rowIndex = 0;
rowIndex ++;
if(rowIndex <= dt.Rows.Count)
{
txtsearbox.Text = dt.Rows[rowIndex]["Admin_no"].ToString();
txtsurname.Text = dt.Rows[rowIndex]["surname"].ToString();
txtfirstname.Text = dt.Rows[rowIndex]["firstname"].ToString();
txtothername.Text = dt.Rows[rowIndex]["othername"].ToString();
txtsex.Text = dt.Rows[rowIndex]["sex"].ToString();
Photo.ImageUrl = dt.Rows[rowIndex]["photo"].ToString();
}
mycon.Close();
}
The error it shows is: There is no row at position 1.
I want to put a combobox in my datagridview. I've tried differents ways (creating a var list<>, creating an arraylist, ect...) and none is working. The thing is my column already exist because of my select query that show my database in the datagridview. But the column is empty since in my database the column is fill with NULL value.
I have two choices : Creating a combobox and do an addcolumn, or if you know how to do it link my combobox to the already existing column. And obviously i need help creating my combobox.
Thank you !
My code :
public partial class Repair : Form
{
public Repair()
{
Main pp = new Main();
InitializeComponent();
this.label4.Text = pp.label3.Text;
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE FComponent IS NOT NULL";
}
else
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
ArrayList list = new ArrayList();
list.Add("C-C");
list.Add("C-O");
combo.Items.AddRange(list.ToArray());
dataGridView1.Columns.Add(combo);
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for(int i=0;i<4;i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataGridView2.Rows)
{
for(int i=0;i<3;i++)
{
dataGridView2.Columns[i].ReadOnly = true;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Main ff = new Main();
ff.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
string Var1 = textBox1.Text;
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailAndPass WHERE BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE SerialNum LIKE #SerialNum AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE SerialNum LIKE #SerialNum And FComponent IS NOT NULL";
}
}
else
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailOnly WHERE (BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent) AND ReportingOperator IS NULL ";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL ";
command1.CommandText = "SELECT DISTINCT Machine, BoardName, BoardNumber FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
}
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[6].Value != null) && (bool)row.Cells[6].Value)
{
SqlCommand command = maConnexion.CreateCommand();
command = new SqlCommand("update FailAndPass set FaultCodeByOp=#Fault, RepairingDate=#RD, RepairingTime = #RT, ReportingOperator=#RO WHERE SerialNum=#Serial", maConnexion);
command.Parameters.AddWithValue("#Fault", row.Cells[4].Value != null ? row.Cells[4].Value : DBNull.Value);
command.Parameters.AddWithValue("#RD", DateTime.Today.ToString("d"));
command.Parameters.AddWithValue("#RT", row.Cells[5].Value != null ? row.Cells[5].Value : DBNull.Value);
command.Parameters.AddWithValue("#RO", this.label4.Text);
command.Parameters.AddWithValue("#Serial", this.textBox1.Text);
command.ExecuteNonQuery();
}
}
maConnexion.Close();
this.Hide();
Repair rep = new Repair();
rep.Show();
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
dataGridView1.Rows[e.RowIndex].Cells[6].Value = true;
}
}
}
private void ComboboxInDatagridview()
{
var dataGridView1 = new DataGridView();
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { combo });
ArrayList list = new ArrayList() { "C-C", "C-O" };
var rowindex = dataGridView1.Rows.Add();
DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1["combo", rowindex];
//Or
//var columnindex = 0;
//DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1[columnindex, rowindex];
cmbCell.DataSource = list;
}
Anyone having other solutions ? I've tried something else :
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
ArrayList list1 = new ArrayList(); //{ "C-C", "C-O", "Absence composant", "Mauvaise valeur", "Mauvais sens", "Mauvais composant" };
list1.Add("C-C");
list1.Add("C-O");
combo.DataSource = list1;
combo.HeaderText = "FaultCodeByOp";
combo.DataPropertyName = "FaultCodeByOp";
dataGridView1.Columns.AddRange(combo);
didnt change anything.
I dont know what i've done, but it is not greyish anymore. Now it is white like other columns.... but it doesnt dropdown, nor show members of the list.
I'm trying to insert 5 records into a SQL Server database table from DataGridView using C#.
From my code it takes input of several records but insert only first record in database. Can anybody help me to save 5 records in database by a single click of save button?
Here is my code:
DataSet ds = new DataSet();
SqlConnection cs = new SqlConnection(#"Data Source=DELL-PC;Initial Catalog=Image_DB;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
BindingSource Input = new BindingSource();
DataView dview = new DataView();
private void Form1_Load(object sender, EventArgs e)
{
//create a DataGridView Image Column
DataGridViewImageColumn dgvImage = new DataGridViewImageColumn();
//set a header test to DataGridView Image Column
dgvImage.HeaderText = "Images";
dgvImage.ImageLayout = DataGridViewImageCellLayout.Stretch;
DataGridViewTextBoxColumn dgvId = new DataGridViewTextBoxColumn();
dgvId.HeaderText = "ID";
DataGridViewTextBoxColumn dgvName = new DataGridViewTextBoxColumn();
dgvName.HeaderText = "Name";
dataGridView1.Columns.Add(dgvId);
dataGridView1.Columns.Add(dgvName);
dataGridView1.Columns.Add(dgvImage);
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.RowTemplate.Height = 120;
dataGridView1.AllowUserToAddRows = false;
}
// button add data to dataGridView
// insert image from pictureBox to dataGridView
private void btn_Add_Click(object sender, EventArgs e)
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
dataGridView1.Rows.Add(txt_UserID.Text, txt_Name.Text, img);
}
// browse image in pictureBox1 Click
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Filter = "Choose Image(*.jpg; *.png; *.gif)|*.jpg; *.png; *.gif";
if (opf.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(opf.FileName);
}
}
private void btn_Save_Click(object sender, EventArgs e)
{
for (int i = 5; i < dataGridView1.Rows.Count; i++)
{
string col1 = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col2 = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col3 = dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string insert_sql = "INSERT INTO Input(UserID, UserName, PassImage) VALUES ('" + col1 + "','" + col2 + "','" + col3 + "')";
this.getcom(insert_sql);
}
MessageBox.Show("Record Added");
}
public SqlConnection GetSqlConnection() //connection function
{
string str_sqlcon = "Data Source=DELL-PC;Initial Catalog=Image_DB;Integrated Security=True";
SqlConnection mycon = new SqlConnection(str_sqlcon);
mycon.Open();
return mycon;
}
public void getcom(string sqlstr) //function for adding rows
{
SqlConnection sqlcon = this.GetSqlConnection(); // Watch out same string type as GetSQLConnection function
SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);
sqlcom.ExecuteNonQuery();
sqlcom.Dispose();
sqlcon.Close();
sqlcon.Dispose();
}
The problem is within this " for " loop, you are not using the i in your for loop.
better try this one.
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string col1 = dataGridView1.Rows[i].Cells[0].Value.ToString();
string col2 = dataGridView1.Rows[i].Cells[1].Value.ToString();
string col3 = dataGridView1.Rows[i].Cells[2].Value.ToString();
string insert_sql = "INSERT INTO Input(UserID, UserName, PassImage) VALUES ('" + col1 + "','" + col2 + "','" + col3 + "')";
this.getcom(insert_sql);
}
change the code logic, if needed.
for (int i = 5; i < dataGridView1.Rows.Count; i++)
change this to for (int i = 0; i < dataGridView1.Rows.Count; i++)
You are assigning 5 to i so after one insert it will come out of the loop because i will become 6.
also include 'i' while specifying the datagridview row..else it will always point to one row and insert 5 rows but of same value
I'm Trying to filter a combo box using its text property in all characters of Items not only Beginning of them. I'm trying below code in TextChanged event of my combo box. but unfortunately combo box resets after entering any key:
private void cmbCompany_TextChanged(object sender, EventArgs e)
{
string QueryCompany = string.Format("select id,title from acc.dl where title LIKE '%" + cmbCompany.Text + "%' union select null , null order by title");
SqlDataAdapter DA1 = new SqlDataAdapter(QueryCompany, con);
DataTable DT1 = new DataTable();
DA1.Fill(DT1);
cmbCompany.DisplayMember = "Title";
cmbCompany.ValueMember = "id";
cmbCompany.DataSource = DT1;
}
connection string "con" is defined and opened.
thanks for your helps.
Below part of code which works for me where searching part works not only at the begining but also in the middle. I paste also additional part responsible for move focus to the next control on the form after you hit enter button.
Initialization part:
public Form1()
{
InitializeComponent();
cmbItems = new List<ComboBoxItem>();
InitializeComboBox();
}
private void InitializeComboBox()
{
Random rand = new Random();
for (int i = 0; i <= 1500; i++)
{
int counter = rand.Next(1, 105000);
cmbItems.Add(new ComboBoxItem("randomNumber" + counter, "ID_" + counter));
}
comboBox1.DataSource = cmbItems;
}
Filtering part:
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
if (comboBox1.Text == string.Empty)
{
comboBox1.DataSource = cmbItems; // cmbItems is a List of ComboBoxItem with some random numbers
comboBox1.SelectedIndex = -1;
}
else
{
string tempStr = comboBox1.Text;
IEnumerable<ComboBoxItem> data = (from m in cmbItems where m.Label.ToLower().Contains(tempStr.ToLower()) select m);
comboBox1.DataSource = null;
comboBox1.Items.Clear();
foreach (var temp in data)
{
comboBox1.Items.Add(temp);
}
comboBox1.DroppedDown = true;
Cursor.Current = Cursors.Default;
comboBox1.SelectedIndex = -1;
comboBox1.Text = tempStr;
comboBox1.Select(comboBox1.Text.Length, 0);
}
}
Moving focus part:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\r') return;
if (this.ActiveControl != null)
{
this.SelectNextControl(this.ActiveControl, true, true, true, true);
}
e.Handled = true; // Mark the event as handled
}
I hope that helps someone.
you can add a textbox to your form and use it's text to filter :
string QueryCompany =
string.Format(
"select id,title from acc.dl where dltype in (2,4) union select null , null order by title");
SqlDataAdapter DA1 = new SqlDataAdapter(QueryCompany, con);
con.Open();
DataTable DT1 = new DataTable();
DA1.Fill(DT1);
con.Close();
DataView dv1 = new DataView(DT1);
dv1.RowFilter = "Title like '%" + txtCompany.Text + "%' or Title is null";
cmbCompany.DisplayMember = "Title";
cmbCompany.ValueMember = "id";
cmbCompany.DataSource = dv1;
and in selected index changed event :
txtCompany.Text = cmbCompany.Text;
My first attempt at performing a search on records in a database; I have a windows form project that upon load event displays a name from an Access database in a textbox. There is more to the form than this, but for practical purposes, I have buttons Previous, Next and a Find. Suppose I have 4 names in the database: 1-Atlas, 2-Benson, 3-Lane & 4-Smith. Form loads and Atlas is displayed. Do a search for Lane and then Lane is displayed on the form. Hit ‘Next’ and instead of Smith, Benson is displayed. I know why it is doing so: the search puts the record in the DataRow ‘returnedRow’ whereas all the records displayed on form load and ‘Previous’ & ‘Next’ are from the DataRow ‘dRow’. How do I retrieve a record from a query that is inside dRow?
OleDbConnection myConn = new OleDbConnection();
DataSet myDS;
int MaxRows = 0
int inc = 0;
private void Form1_Load(object sender, EventArgs e)
{
myConn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Testing\TestDatabase.accdb";
myConn.Open();
myDS = new DataSet();
string sql = "SELECT * From Test";
OleDbDataAdapter myDA = new OleDbDataAdapter(sql, myConn);
myDA.Fill(myDS, "People");
NavigateRecords();
MaxRows = myDS.Tables["People"].Rows.Count;
myConn.Close();
}
private void NavigateRecords()
{
DataRow dRow = myDS.Tables["People"].Rows[inc];
txtName.Text = dRow.ItemArray.GetValue(1).ToString();
txtAddress.Text = dRow.ItemArray.GetValue(2).ToString();
txtCity.Text = dRow.ItemArray.GetValue(3).ToString();
txtState.Text = dRow.ItemArray.GetValue(4).ToString();
txtZip.Text = dRow.ItemArray.GetValue(5).ToString();
}
private void btnNext_Click(object sender, EventArgs e)
{
if (inc != MaxRows - 1)
{
inc++;
NavigateRecords();
}
else
{
MessageBox.Show("No more rows");
}
}
private void btnFind_Click(object sender, EventArgs e)
{
string searchFor = txtFind.Text;
int results = 0;
if (txtFind.Text.Trim() == "")
{
MessageBox.Show("Nothing to search for");
return;
}
DataRow[] returnedRows;
string expression;
expression = "Name1='" + searchFor + "'";
returnedRows = myDS.Tables["People"].Select(expression);
results = returnedRows.Length;
if (results > 0)
{
DataRow dr1;
dr1 = returnedRows[0];
txtName.Text = dr1[1].ToString();
txtAddress.Text = dr1[2].ToString();
txtCity.Text = dr1[3].ToString();
txtState.Text = dr1[4].ToString();
txtZip.Text = dr1[5].ToString();
}
else
{
MessageBox.Show("No record found");
}
}
You mean this part ... ?
private void NavigateRecords()
{
DataRow dRow = myDS.Tables["People"].Rows[inc];
txtName.Text = dRow[1];
txtAddress.Text = dRow[2];
txtCity.Text = dRow[3];
txtState.Text = dRow[4];
txtZip.Text = dRow[5];
}