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));
}
Related
This is my code to display table value to a DropDownList.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString))
{
con.Open();
string str="SELECT ItemOne,ItemTwo,ItemThree FROM tableItem";
using (SqlCommand cmd = new SqlCommand(str, con))
{
SqlDataAdapter dA=new SqlDataAdapter(cmd);
dA.Fill(dT);
DropDownList1.DataSource = dT;
DropDownList1.DataValueField = "ItemTwo";
DropDownList1.DataTextField = "ItemOne";
DropDownList1.DataBind();
}
This is to display the selected value of DropDownList to a TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = //Get the value of ItemThree here
}
My problem is: How will I display the column value of ItemThree in another TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropDownList1.Items[2].ToString(); // 2 is your index
}
Another way of doing this
var connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
var sql = "SELECT ItemOne, ItemTwo, ItemThree FROM tableItem";
using (var table = new DataTable) {
using (var adapter = new SqlDataAdapter(sql, connectionString)
adapter.Fill(table);
foreach (DataRow dr in table.Rows)
DropDownList1.Items.Add(new ListItem(dr["ItemTwo"], dr["ItemTwo"]) {
Tag = dr["ItemThree"]
});
}
Then from the event handler
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropdownList1.SelectedItem.Tag.ToString();
}
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
We want to attach a combo box into a cell of data grid view. Now it works with mouse click. but for faster moving of form we need it to work using keyboard.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void CreateGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("EmpName", typeof(string));//0
dt.Columns.Add("EmpID", typeof(int));//1
dt.Columns.Add("PhoneNo", typeof(string));//2
dt.Columns.Add("Address", typeof(string));//3
dt.Columns.Add("Email", typeof(string));//4
dataGridView1.DataSource = dt;
dataGridView1.Controls.Add(comboBox1); // Add System.Windows.Form.ComboBox in Datagridview
}
private void Form1_Load(object sender, EventArgs e)
{
CreateGrid();
fillRecords(1);
}
string SQL;
void fillRecords(int QueryNo)
{
SqlConnection con = new SqlConnection(#"Data Source=APPLE-PC\RNS;Initial Catalog=DemoDatabase;User ID=sa;Password=rns11");
con.Open();
if (QueryNo==1)
{
SQL = "Select EmpName,EmpID from EmployeeMaster";
}
else if (QueryNo==2)
{
SQL = "Select PhoneNo,Address from EmployeeMaster where EmpID=" + comboBox1.SelectedValue.ToString();
}
SqlDataAdapter da = new SqlDataAdapter(SQL, con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if (QueryNo == 1)
{
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "EmpName";
comboBox1.ValueMember = "EmpID";
}
else if (QueryNo == 2)
{
dataGridView1.CurrentRow.Cells[1].Value = comboBox1.SelectedValue.ToString();
dataGridView1.CurrentRow.Cells[0].Value = comboBox1.Text;
DataRow dr=dt.Rows[0];
dataGridView1.CurrentRow.Cells[2].Value = dr["PhoneNo"];
dataGridView1.CurrentRow.Cells[3].Value = dr["Address"];
}
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
//Visible Location on Current Cell
if (dataGridView1.CurrentCell.ColumnIndex==0)
{
comboBox1.Visible = true;
comboBox1.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Size = dataGridView1.CurrentCell.Size;
}
}
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
comboBox1.Visible = false;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue.ToString()!="System.Data.DataRowView")
{
fillRecords(2);
}
}
}
this solution is given by Sinisa Hajnal.
It should work using keyboard, but usually need to press F2 first to enter edit mode. I can solve this by handling CellEnter event and opening edit mode for combobox and setting focus to it inside.
`
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex==0)
{
comboBox1.Visible = true;
comboBox1.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Size = dataGridView1.CurrentCell.Size;
comboBox1_SelectedIndexChanged(null, null);
comboBox1.Focus();//focus on Combobox
}
}
`
I want to display the date which is selected in another form using monthCalender control..
Here is my code..
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
ActivityScheduler frm1 = new ActivityScheduler();
frm1.Show();
}
private void ActivityScheduler_Load(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
RemainderPopUp frm = new RemainderPopUp();
string s = "select * from [Activity_Scheduler]";
SqlCommand sCmd = new SqlCommand(s, con);
SqlDataAdapter da = new SqlDataAdapter(sCmd);
DataSet ds = new DataSet();
da.Fill(ds, "[Activity_Scheduler]");
datagridActivityScheduler.DataSource = ds.Tables[0];
datagridActivityScheduler.AllowUserToAddRows = true;
DataTable dt = new DataTable();
dt = ds.Tables["Activity_Scheduler"];
if (dt == null)
{
datagridActivityScheduler.Rows[0].Cells[3].Value = frm.monthCalendar1.SelectionRange.Start.ToShortDateString();
MessageBox.Show(datagridActivityScheduler.Rows[0].Cells[3].Value.ToString());
}
con.Close();
}
It is displaying the correct value in messagebox..but the value is not displaying in datagridview...
Plz anybody help me out..
Try Following Code :
form_load()
{
private string myDate="1999/12/12";
// Declare a Date property of type string:
public string Name
{
get
{
return myDate;
}
set
{
myName = value;
}
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
ActivityScheduler frm1 = new ActivityScheduler();
ActivityScheduler.myDate = frm.monthCalendar1.SelectionRange.Start.ToShortDateString()
frm1.Show();
}
Now you can get date on other form as :
string myDate = frm1.myDate();
Let me know if any queries.
I want to populate TWO dropdownlist, based on selection of first dropdownlist the second dropdownlist will get populated.
Example :
Like i have two dropdownlist namely 1.ddlCountry and 2.ddlState
Now when country is selected then depending on the selected Country the States related with that Country will get populated in the State dropdownlist. I want to achieve this withour reloading the whole page in Asp.Net with coding language as C#.
How can i achieve the same?
Dropdownlist is fetching data from database by executing query.
You can use AJAX toolkit CascadingDropDown as told by Naresh.
OR
use ajax update panel and keep all Dropdowns in it. So the whole page will not load on changing dropdown value.
You didnt give the code to further solution.
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
FillStateByCountry();
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
FillLocationByCountryandState();
}
private void FillStateByCountry()
{
DataSet dstFillState;
int CountryId = Convert.ToInt32(ddlCountry.SelectedValue.ToString());
dstFillState = Tbl_State.FillDDLState(CountryId);
ddlState.DataSource = dstFillState;
ddlState.DataTextField = "State";
ddlState.DataValueField = "Id";
ddlState.DataBind();
}
similarly FillLocationByCountryandState();
Add two dropdownlists to your form and name it as cmbStates, cmbCities
when you select state name from cmbStates(dropwdownlist), cmbCities(dropdownlist) generates cities based on state name(cmbStates)
by fetching data from database
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=pbs-server;database=p2p;user id=shekar;password=sekhar#1346");
SqlCommand cmd = new SqlCommand("select states from Country", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "Country");
cmbStates.DataSource = ds.Tables[0];
cmbStates.SelectedValue = 0;
con.Close();
}
private void cmbStates_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=xxxx;database=xxxx;user id=xxxxr;password=xxxxxx");
SqlCommand cmd = new SqlCommand("select cities from States where cityname = 'cmbStates.SelectedItem.ToString()'", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "States");
cmbCities.DataSource = ds.Tables[0];
cmbCities.SelectedValue = 0;
con.Close();
}
OR
manually adding items
namespace DropDownlist
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmbStates.Items.Add("Andhra Pradesh");
cmbStates.Items.Add("Tamilnadu");
cmbStates.Items.Add("Karnataka");
cmbStates.SelectedValue = 0;
}
private void cmbStates_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbStates.SelectedItem.ToString() == "Andhra Pradesh")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Hyderabad");
cmbCities.Items.Add("Guntur");
cmbCities.Items.Add("Vijayawada");
cmbCities.SelectedValue = 0;
}
else if (cmbStates.SelectedItem.ToString() == "Tamilnadu")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Chennai");
cmbCities.Items.Add("Coimbatore");
cmbCities.Items.Add("ooty");
cmbCities.SelectedValue = 0;
}
else if (cmbStates.SelectedItem.ToString() == "Karnataka")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Bangalore");
cmbCities.Items.Add("Mangalore");
cmbCities.SelectedValue = 0;
}
else
{
MessageBox.Show("Please Select any value");
}
}
}
}