I am developing an application using Winforms and C#. I have a class which will fetch master data of one table. The function in the class executes a stored procedure which returns 2 columns of data.
I have one form, which has a Listbox control, TextBox and ComboBox. I would like to:
Display entire data for column 1 on List box.
Display column 1 selected row value on Textbox and column 2 value in Combo Box for the selected row. Value changes based on selection change in Listbox.
Code to get data using the stored procedure:
public void GetDeity()
{
cmd = new SqlCommand();
cmd.Connection = conDB;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "get_DeityMaster";
cmd.ExecuteNonQuery();
return;
}
ListBox Name: lstDeityList
TextBox Name: txtDeityName
ComboBox Name: cmbDeityCategoryName
Please help on how to pass data. Thanks
you need to return data from your method like below, currently your method return nothing.
you may need to change the method implementation to return DataTable or DataSet
public DataTable GetDeity()
{
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand("get_DeityMaster", sqlConn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
Now you can bind the Listbox control using returned datatable above, when selected item change event you can bind other text box and combo boxes.
in your Form you can call the class method by creating object of class like below
Yourclass obj = new Yourclass();
DataTable dt= obj.GetDeity();
ListBox1.DataSource = dt;
ListBox1.DisplayMember = "Column1Name";
ListBox1.ValueMember = "Column2Name";
You need to add SelectedIndexChanged event for the ListBox1
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
TextBox1.Text = ((DataRowView)ListBox1.SelectedItem).Row.ItemArray[0].ToString();
// bind the ComboBox as well
}
Change return type of function from void to DataTable. Create SQLAdapter with your command and fill DataTable.
public DataTable GetDeity()
{
DataTable mTable = new DataTable();
cmd = new SqlCommand();
cmd.Connection = conDB;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "get_DeityMaster";
SqlAapter mAdapter = new SqlAdapter(cmd);
mAdapter.Fill(mTable);
return mTable
}
Why don't you hold the fetched data in a datatable. Then assign columns of that datatable to different controls you like.
e.g.
public void GetData()
{
DataTable odt = new DataTable();
odt = obj.GetDeity();
Combobox.DataSource = odt;
.......... set other controls also...
}
public DataTable GetDeity()
{
SqlCommand cmd = new SqlCommand("get_DeityMaster");
cmd.CommandType = CommandType.StoredProcedure;
return getdatatable(cmd); // YOUR DATA FETCHING LOGIC
}
Related
I am new to .net world and I could not figure out why the below code does not work. I have a dropdownlist populated with DEPARTMENT_NAME and value as DEPARTMENT_ID. I have a gridview which populates the employees data based on department_id selected from dropdown list. I have written the following code but the gridview is not populating. Can someone please help what I am doing wrong here.
protected void ddDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
OracleConnection oConn = new OracleConnection(connStr);
oConn.Open();
string SqlText = "Select * from employees where department_id = :department_id";
OracleCommand cmd = new OracleCommand(SqlText, oConn);
cmd.CommandType = CommandType.Text;
OracleParameter p_department_id = new OracleParameter();
p_department_id.OracleDbType = OracleDbType.Varchar2;
p_department_id.Value = ddDepartments.SelectedItem.Value;
cmd.Parameters.Add(p_department_id);
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
DataTable dtEmployees = new DataTable();
adapter.Fill(dtEmployees);
gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();
dtEmployees.Dispose();
adapter.Dispose();
cmd.Dispose();
oConn.Close();
oConn.Dispose();
}
You need to use a Session variable to persist the gridView datasource on Postback which is sent by the dropdownlist.
So right after:
gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();
Add:
Session("gvDS") = gvEmployees.DataSource;
In the page Load() method:
if (Session["gvDS"] != null && IsPostBack)
{
gvEmployees.DataSource = Session["gvDS"];
gvEmployees.DataBind();
}
else
BindGridView(); // you initial gvEmployees binding method
Please see my answer #:
Asp.net Web Forms GridView Dynamic Column Issue
My windows form application having Datagridview with combobox I need to set the first value for example ("Select item")
My result
Expected Result
DataGridViewComboBoxColumn cmd_item =(DataGridViewComboBoxColumn)(invoice_datagrid.Columns["cmb_gridItem"]);
DataTable dt = new DataTable();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT DISTINCT item_name,sales_rate.item_id FROM sales_rate JOIN items ON sales_rate.item_id=items.item_id", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
cmd_item.DisplayMember = "item_name";
cmd_item.ValueMember = "item_id";
cmd_item.DataSource = dt;
con.Close();
First you need to add an entry in your database for the select item text
....
da.SelectCommand = cmd;
da.Fill(dt);
// Add a fake record to the table with id = -1 to recognize it
DataRow r = dt.NewRow();
r.ItemArray = new object[] {"select item", -1};
// Insert the new row in the first position of your table
dt.Rows.InsertAt(r, 0);
cmd_item.DisplayMember = "item_name";
cmd_item.ValueMember = "item_id";
cmd_item.DataSource = dt;
con.Close();
Now the value displayed by default in the combo for your rows depends on the value for that column in the datasource of your grid.
So, for example, if a row in your grid has the value -1 for the column where you have the ComboBox then the entry "select item" will be showed.
EDIT
It seems that you want a default value for your ComboBox column when you add a new record to the gridview. In this case Microsoft suggest to use the event DefaultValuesNeeded. In the event handler you can set the cell value to the desidered value to show the select item text.
private void invoice_datagrid_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
// Set the default value for the combobox column in new rows.
e.Row.Cells("combobox_column_key").Value = -1
}
Here combobox_column_key should be replaced by the key for the column with the combobox
I am trying to populate a dropdown list on pageload with data from the batabase.
While populating I want the dropdown items (<option>) to have the display text which is different from 'value' of the <option>
For example: The dropdown list will show "Title" (column from db) as text on UI, but the 'value' of the <option> should be "ID" (column from db)
How do I achieve this?
Currently my code is like this: (drpReleaseTitle is the ID of the dropdown)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
con1.Open();
SqlCommand releaseTitlecmd = new SqlCommand("select Title from LWMDemo_ReleaseInfo order by ReleaseID", con1);
SqlDataReader releaseTitledr = releaseTitlecmd.ExecuteReader();
while (releaseTitledr.Read())
{
drpReleaseTitle.Items.Add(releaseTitledr.GetValue(0).ToString());
}
con1.Close();
}
}
Try this
drpReleaseTitle.Items.Add(new ListItem("yourtext", "yourvalue"));
It is better to Use Dataset Instead of Data Reader Because it use disconnected architecture so You can Use After Close the connection
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
con1.Open();
SqlCommand releaseTitlecmd = new SqlCommand("select Title from LWMDemo_ReleaseInfo order by ReleaseID", con1);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = Cmd;
sda.Fill(ds);
if(ds!=null && ds.table.count>0){
if(ds.table[0]!=null && ds.table[0].rows.count>0){
drpReleaseTitle.DataSource=ds.table[0].Title; //Title Column
drpReleaseTitle.DataSourceID=ds.table[0].ID; //ID Column
}
}
con1.Close();
}
}
If you will try add a string to Items in drop down list, it will create a item, that will have text and value as your string. You need to add new ListItem. ListItem contains constructor with text and value as parameters. More about this class you can read here
I am a newbie to c#.net winforms application. I have a data grid wch displays some data and out of which one of the column shud be made a dropdownlist or combobox. how do I use that in my code. please help.
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
DataGridViewComboBoxColumn combo = (DataGridViewComboBoxColumn)dataGridView1.Rows[e.RowIndex].Cells[3].OwningColumn;
sql = "select NAME FROM Suppliers";
BindingSource bsource = new BindingSource();
bsource.DataSource = obj.SqlDataTable(sql);
dataGridView1.DataSource = bsource;
combo.HeaderText = "Select Supplier";
}
I want to populate the 3rd column of the data grid with supplier name from the corresponding suppliers table.The data grid view is already populated with data from a join query and one of the field is Supplier(wch I mwant to convert to a dropdown or combo box). let me know if you need any further info for clarifications.
I Modified my code as follows:
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Suppliers";
//execute sql data adapter to get supplier values
DataTable dt = obj.SqlDataTable("select NAME from CUSTOMERS");
foreach (DataRow supplier in dt.DataSet.Tables[0].Rows)
{
combo.Items.Add(supplier[0]);
}
dataGridView1.Columns.Add(combo);
now am getting a null reference exception at " dt.DataSet.Tables[0].Rows"
. plz help. I am not sure if am missing something.
Try this code
string strcon = #"Data Source=kp;Initial Catalog=Name;Integrated Security=True;Pooling=False";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataGridViewComboBoxColumn dgvCmb;
public Form2()
{
InitializeComponent();
grdcmd();
}
public void grdcmd()
{
con = new SqlConnection(strcon);
con.Open();
string qry = "Select * from Dbname";
da = new SqlDataAdapter(qry, strcon);
dt = new DataTable();
da.Fill(dt);
dgvCmb = new DataGridViewComboBoxColumn();
foreach (DataRow row in dt.Rows)
{
dgvCmb.Items.Add(row["Fname"].ToString());
}
dataGridView1.Columns.Add(dgvCmb);
}
Here I am getting the values to my grid. This is Connection of my database table. It is okay and working well but i want to show my Qty field data by dividing my txtOrderQuantity (textbox id name)value.
<asp:TextBox ID="txtOrderQuantity" runat="server"
ontextchanged="txtOrderQuantity_TextChanged" AutoPostBack="true"> </asp:TextBox>
How i can show my grid view field by dividing by 2 with txtorderQuantity.
public DataTable GetData()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
SqlDataAdapter sa = new SqlDataAdapter();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [RmId],[RmName],[MeasuringUnit],[Rate],[Qty],[BagSz]FROM [dbo].[RawMaterials]",con);
sa.SelectCommand = cmd;
sa.Fill(dt);
con.Close();
return dt;
}
you can do it two ways.
1) you can send the value of the text field to your GetData() method. and then prepare your select statement in the following way
public DataTable GetData(int OrderQuantity)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
SqlDataAdapter sa = new SqlDataAdapter();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [RmId],[RmName],[MeasuringUnit],[Rate],([Qty]/OrderQuantity )as Qty,[BagSz]FROM [dbo].[RawMaterials]",con);
sa.SelectCommand = cmd;
sa.Fill(dt);
con.Close();
return dt;
}
2) you can use RowDataBound Event of GridView. it occurs when a single DataRow have bound in the gridView.
void YourGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Display the company name in italics.
// I assume the index of Qty column is 4
e.Row.Cells[4].Text = decimal.Parse(e.Row.Cells[4].Text)/decimal.Parse(txtOrderQuantity.Text) ;
}
}
Use RowDataBound event of gridview and perform following steps:
Find the textbox control and its value.
Find the MyQty value and divide it with textbox value(use specific type cast wherever needed.)
Find your control to display MyQty valud and assign calculated value.