Filling the grid - c#

I wanna fill grid with a background worker but I don't know where I must add DataGrid.DataSource=DataTable; is there any simple example that explain how can I use background worker for filling DataGrid?
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
setgride();
}
private void setgride()
{
string constring = "constring";
SqlCommand com = new SqlCommand();
SqlConnection con = new SqlConnection(constring);
com.Connection = con;
com.CommandText = " select * from Request";
SqlDataAdapter adapt = new SqlDataAdapter(com);
DataTable dt2 = new DataTable();
adapt.Fill(dt2);
propdt2 = dt2;
}
private void button1_Click(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}

in BackgroundWorker.RunWorkerCompleted Event , handle this event and assign source property here.

Related

How do I automatically reload the gridview after adding the new name?

I have to automatically reload the gridview which contains the list of the brand names. What should be done to automatically reload the data gridview when the "Brand has been added" meessage is shown.I have the data gridview in another form.
public partial class AddBrand : Form
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
DBConnection dbcon = new DBConnection();
public AddBrand()
{
InitializeComponent();
cn = new SqlConnection(dbcon.MyConnection());
}
private void Clear()
{
btnSave.Enabled = true;
btnUpdate.Enabled = false;
tbBrand.Clear();
tbBrand.Focus();
}
private void BtnSave_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Do you want to save this brand?", " ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
cn.Open();
cm = new SqlCommand("INSERT INTO tblBrand(brand)VALUES(#brand)", cn);
cm.Parameters.AddWithValue("#brand", tbBrand.Text);
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Brand has been added.");
Clear();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
}
private void btnClose_Click(object sender, EventArgs e)
{
Brand brand = new Brand();
brand.ShowDialog();
}
}
This is the design:
Hope as per your code Brand is the form showing GridView. In this form you can open the form AddBrand.
var addBrand = new AddBrand();
var result = addBrand.ShowDialog();
if(result == DialogResult.Yes)
ReloadLogic()// you can read from db
In BtnSave_Click event in Brand form you can write
this.DialogResult = DialogResult.Yes; Close();
If you want to reload the datagridview when the "Brand has been added" meessage is shown, you can read data to datagridview again.
You can refer to the following code in the form containing datagridview:
private void Form1_Load(object sender, System.EventArgs e)
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
DBConnection dbcon = new DBConnection();
cn = new SqlConnection(dbcon.MyConnection());
cn.open();
string sql = "select * from tblBrand";
SqlDataAdapter sda = new SqlDataAdapter(sql, cn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
cn.close();
}

choose name from dropownlist and associated ID appear in textbox

this is my code for populating a dropdown list with customers name.
protected void Page_Load(object sender, EventArgs e)
{
//Creating a connection to my database using the connection string
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
{
SqlCommand cmd = new SqlCommand("Select CustomerName from Customer", con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList1.DataTextField = "CustomerName";
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
}
}
I want to be able too; when this name is chosen from the dropdownlist box , the associated customer ID will appear in a textbox.
thanks!
It should be as simple as this, by the looks of it:
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue
}
Assuming you have a textbox whose ID is TextBox1.
Alternatively if you want to display the text from the dropdown list (as opposed to the ID value), then simply:
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedItem.Text
}

C# Master Detail gridview on SelectionChanged

I have one form with grid(dataGridView1) and textbox(txtSearch). When I type something in textbox grid filter by field acSubject. Now I put second grid and I want new Custom SQL query which will be depend on selected row in dataGridView1.
SQL would be:
select anUserID from the_setsubjcontact where acSubject = #acSubject
How can I do this?
Code is:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=local\s08r2;Initial Catalog=Demo;User id=sa;Password=sa";
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(#"
SELECT acSubject, acAddress, acPost, acName, acPhone,
acFieldSA, acFieldSB, acFieldSC, acFieldSD, acFieldSE,
anFieldNA, anFieldNB, anFieldNC, anFieldND, anFieldNE, OdgovornaOsoba, acSubjTypeBuyer
FROM ARS.dbo._ARSCRM_vSubjekti
", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtSearch.Text))
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
}
else
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("acSubject like '%{0}%'", txtSearch.Text);
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//User selected a cell (show the first cell in the row)
if (dgv.SelectedCells.Count > 0)
txtAcFieldSA.Text = dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[5].Value.ToString();
}
}
I was success when I use DataSet from C#, but with CustomSQL I don't know how to do that.
private void ShowDetails(int UserId)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=local\s08r2;Initial Catalog=Demo;User id=sa;Password=sa";
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(#"
select anUserID from the_setsubjcontact where acSubject = #acSubjec", con);
da.SelectCommand.Parameters.AddWithValue(#acSubjec, UserId.ToString());
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView2.DataSource = dt;
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//User selected a cell (show the first cell in the row)
if (dgv.SelectedCells.Count > 0 && dgv.SelectedCells[0].RowIndex >-1 && dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells.Count > 0)
txtAcFieldSA.Text = dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[0].Value.ToString();
ShowDetails(int.Parse(txtAcFieldSA.Text));
}

how to display value in listbox from dataview

i have a textbox and listbox in a winform app. when i type a value(i.e,string) in the textbox i want the listbox to show the values from datatable and when i am selecting a particular value from listbox it will display in textbox .
code:
private void txtIName_TextChanged(object sender, EventArgs e)
{
string constring = "Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin#123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT distinct * FROM Item_Details", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (dt = new DataTable())
{
sda.Fill(dt);
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
listBox1.Visible = true;
listBox1.DataSource = dv;
}
}
}
}
}
but i got the output in listbox like "system.data.datarow". By debugging i can seen that rows which i want, in dataview 'dv'. what i am missing here? thanks.
You don't need to load data each time the TextChanged event fires. It's enough to load data in Load event of your form and then in TextChanged just filter the data. Then using an event like DoubleClick of ListBox set the text of TextBox:
private DataTable dataTable = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
string constring = #"Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin#123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT distinct * FROM Item_Details", con))
{
sda.Fill(dataTable);
}
}
this.listBox1.DataSource = new DataView(dataTable);
this.listBox1.DisplayMember = "IName";
this.listBox1.Visible = false;
}
private void txtIName_TextChanged(object sender, EventArgs e)
{
var dv = (DataView)this.listBox1.DataSource;
dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
listBox1.Visible = true;
}
private void listBox1_DoubleClick(object sender, EventArgs e)
{
var item = (DataRowView)listBox1.SelectedItem;
if (item != null)
this.txtIName.Text = item["IName"].ToString();
else
this.txtIName.Text = "";
this.listBox1.Visible = false;
}
Don't forget to attach Form1_Load, txtIName_TextChanged and listBox1_DoubleClick handlers to events.
You must specify your DisplayMember, it must be some Field in your DataView
listBox1.DisplayMember = "Your Field"
then you can suscribe to the event SelectedValueChanged :
listBox1.SelectedValueChanged += new EventHandler(listBox1_SelectedValueChanged);
visual studio create for you an event handler
void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
// you get your selected item here
}
hope it helps

"System.Data.DataRowView" in form load using combobox in C#

Every time my forms loads/open it will prompt "System.Data.DataRowView", How can I possibly remove this?
Here is my code:
{
InitializeComponent();
GetProcessorCardTypes();
}
private void GetProcessorCardTypes()
{
cn.Open();
MySqlCommand cmd = new MySqlCommand("call GetProcessorMethod(1)", cn);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
cmbProcessorMethods.DataSource = dt;
cmbProcessorMethods.ValueMember = "method_id";
cmbProcessorMethods.DisplayMember = "method_name";
}
private void cmbProcessorMethods_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show(cmbProcessorMethods.SelectedValue.ToString());
}
If you want to completely remove message box, then remove cmbProcessorMethods_SelectedIndexChanged event handler. Or you can change it to display method_name of selected row:
private void cmbProcessorMethods_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView row = (DataRowView)cmbProcessorMethods.SelectedItem;
MessageBox.Show(row["method_name"].ToString());
}
As Derek pointed, just set DisplayMember and ValueMember properties before assigning data source and your original code will work:
cmbProcessorMethods.ValueMember = "method_id";
cmbProcessorMethods.DisplayMember = "method_name";
cmbProcessorMethods.DataSource = dt;

Categories