How to bind a dropdownlist with a label - c#

I have two SP's, both doing different things but they are connected by the I.d's... how can i bind these so that the label changes with the dropdown selection?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Refreshdata(214, DateTime.Today, DateTime.Today.AddDays(1).AddMinutes(-1));
BindDropDownList();
LabelCount(214, DateTime.Today, DateTime.Today.AddDays(1).AddMinutes(-1));
}
}
private void BindDropDownList()
{
BizManager mgr = new BizManager();
DataView dv = mgr.GetItemSeriesMaster().DefaultView; //how to filter data
dv.RowFilter = ProductQueryFilter;
Dropdownlist1.DataSource = dv; //datasource == usp.getitemseriesmaster
Dropdownlist1.DataTextField = "Description"; // the items to be displayed in the list items
Dropdownlist1.DataValueField = "Id"; // the id of the items displayed
Dropdownlist1.DataBind();
}
private string ProductQueryFilter
{
get
{
return ConfigurationManager.AppSettings["ProductQueryFilter"];
} //returns itemseriesmaster 214 or 225 from web config key.
}
public void Refreshdata(int selectedProduct, DateTime shiftStart, DateTime shiftEnd)
{
BizManager biz = new BizManager();
GridView1.DataSource = biz.GetPacktstatisticsForShift( //passing in the usp
shiftStart
, shiftEnd
, selectedProduct).DefaultView; //passing in the parameters for the usp
GridView1.DataBind();
}
public void Dropdownlist1_SelectedIndexChanged(object sender, EventArgs e) //this fires after a DDL selection
{
DateTime shiftStart = DateTime.Today; //declaring the param at today - As below
DateTime shiftEnd = DateTime.Today.AddDays(1).AddMinutes(-1);
int productId; //declaring product ID
if (int.TryParse(Dropdownlist1.SelectedValue, out productId))
Refreshdata(productId, shiftStart, shiftEnd);
}
public void LabelCount(int seriesMasterId, DateTime shiftStart, DateTime shiftEnd)
{
{
}
So, i am really stuck here, my label is placed inside a form view as i only need one record that updates very regular. I know the bottom method is not a form view but i was hoping there maybe a work around without using the form view. But i do not see any way to do this even after hours of searching the internet.

Related

selected index value in C# with combobox with database

I am new in c# and I have a question.
I want to select a value from a combobox and it should show in a label it's age.
What I do is this:
public void FillCombo()
{
SqlDataAdapter adap = new SqlDataAdapter("Select * from customers",con);
DataTable dt = new DataTable();
adap.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "id";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from customers where name=#name ", con);
cmd1.Parameters.AddWithValue("#name",comboBox1.SelectedItem));
int i= cmd1.ExecuteNonQuery();
if (i > 0)
{
SqlDataReader sqlrdr = cmd1.ExecuteReader();
while (sqlrdr.Read())
{
String age= sqlrdr["age"].ToString();
label1.Text = age;
}
}
else{
MessageBox.Show("no value");
}
con.Close();
}
It shows no value message , even if i have values in database. What can I do?
When you set the DataSource to a DataTable then every item in the combobox is a DataRowView. So you already have the info about the age of the current customer in the combobox. No need to make another call to the database.
You just need to use the SelectedItem property to retrieve the info about the age field or any other field present in the DataSource
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView rv = l.SelectedItem as DataRowView;
// For safety, always check for null.
// It is possible that SelectedIndexChanged
// will be called even when there is no selection in the combobox
if(rv != null)
{
label1.Text = rv["age"].ToString();
....
}
}
Try this to obtain index,value and selected name:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
int selectedValue = (int)cmb.SelectedValue;
ComboboxItem selectedName = (ComboboxItem)cmb.SelectedItem;
}

SelectedIndex is always 0 in dropdownlist(asp.net c#)

I am retrieving data from table Technology in dropdownlist ddlTechnology .
I have TechnologyId as primary key in the table and values are 1,2,3,4
Now as per the technology,i have to add questions in question bank. but when i select any item in dropdownlist, my SelectedIndex is always 0.
i want TechnologyId from dropdownlist.
i have tried following code but its not working
using (dbDataContext dt = new dbDataContext())
{
var qry = from i in dt.Technologies
select i;
ddlTechnology.DataSource = qry;
ddlTechnology.DataValueField = "TechnologyId";
ddlTechnology.DataTextField = "TechnologyName";
ddlTechnology.DataBind();
ddlTechnology.Items.Insert(0, new ListItem("Select Technology", ""));
}
Add button to add question according to selected technology.
protected void btnAdd_Click(object sender, EventArgs e)
{
using (dbDataContext dt = new dbDataContext())
{
Question objQtn = new Question();
objQtn.Question1 = txtQuestion.Text;
objQtn.Option1 = txtOption1.Text;
objQtn.Option2 = txtOption2.Text;
objQtn.Option3 = txtOption3.Text;
objQtn.Answer = txtAnswer.Text;
// below here selectedIndex is always zero..
objQtn.TechnologyId = ddlTechnology.SelectedIndex;
dt.Questions.InsertOnSubmit(objQtn);
dt.SubmitChanges();
txtAnswer.Text = "";
txtOption1.Text = "";
txtOption2.Text = "";
txtOption3.Text = "";
txtQuestion.Text = "";
}
}
Reason1:
Seems like you are binding dropdownlist on every postback. If that is a problem then keeping your load code in !IsPostBack shou work.
if(!IsPostBack)
{
using (dbDataContext dt = new dbDataContext())
{
var qry = from i in dt.Technologies
select i;
ddlTechnology.DataSource = qry;
ddlTechnology.DataValueField = "TechnologyId";
ddlTechnology.DataTextField = "TechnologyName";
ddlTechnology.DataBind();
ddlTechnology.Items.Insert(0, new ListItem("Select Technology", ""));
}
}
Reason 2:
In some cases if programmer disables ViewState property of any control/page then also control looses it's value on postback.
Need to bind dropdown list in the below event.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Bind your dropdown list
}
}
Please find the code for ref. hope it will help you:
(objQtn.TechnologyId = ddlTechnology.SelectedIndex;)
one of these two is of string type check once.
Index.aspx
<asp:DropDownList ID="ddlCloth" runat="server"></asp:DropDownList>
<asp:Button runat="server" ID="btnSave" OnClick="btnSave_Click" />
Index.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt1 = new DataTable();
dt1.Columns.AddRange(new DataColumn[2] { new DataColumn("Id"), new DataColumn("Name") });
dt1.Rows.Add(1, "Shirt");
dt1.Rows.Add(2, "Jeans");
ddlCloth.DataSource = dt1;
ddlCloth.DataTextField = "Name";
ddlCloth.DataValueField = "Id";
ddlCloth.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(ddlCloth.SelectedItem.Value);
string text = Convert.ToString(ddlCloth.SelectedItem.Text);
int index=Convert.ToInt32(ddlCloth.SelectedIndex);
}

populate combobox depending on another combobox

im making a wpf wherein one combobox populates depending on another combobox. however, only one combobox populated.
this is my code below.
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
this.Load += Form4_Load;
}
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
private void Form4_Load(object sender, EventArgs e)
{
string query = "SELECT * FROM data_organsystem";
fillCombo(comboBox3, query, "name", "id");
comboBox3_SelectedIndexChanged(null, null);
}
private void fillCombo(ComboBox combo, string query, string displayMember, string valueMember)
{
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
combo.DataSource = dt;
combo.DisplayMember = displayMember;
combo.ValueMember = valueMember;
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
int val;
Int32.TryParse(comboBox3.SelectedValue.ToString(), out val);
string query = "SELECT * FROM data_symptom WHERE organ_system_id = " + val;
fillCombo(comboBox4, query, "name", "id");
}
}
}
if you have any idea on how to edit this code, it would be a big help. thanks!
You will get error when you executing method comboBox3_SelectedIndexChanged àt the line
Int32.TryParse(comboBox3.SelectedValue.ToString(), out val);
Because comboBox3.SelectedValue is null if no item selected in the ComboBox, I didn't see in your code that you selected some items before calling comboBox3_SelectedIndexChanged first time.
Because method comboBox3_SelectedIndexChanged executed inside Form.Load eventhandler exception wasn't shown. Check this: https://stackoverflow.com/a/3209813/1565525.
That is why you didn't get any errors
You need to check SelectedValue for null before using it
If(this.comboBox3.SelectedValue is null)
{
this.comboBox4.DataSource = null; //Remove all items if nothing selected
}
else
{
Int32 val= (Int32)this.ComboBox3.SelectedValue;
string query = "SELECT id, name FROM data_symptom WHERE organ_system_id = " + val;
fillCombo(this.comboBox4, query, "name", "id");
}
Because you using DataBinding when filling ComboBox with items it will be logically to use SelectedValueChanged event handler
private void comboBox3_SelectedValueChanged(object sender, EventsArgs e)
{
//same code
}
You never add comboBox4 to your form. comboBox3 is added via constructor but comboBox4 is created and added to nowhere.

How to transfer data contained in a textbox to a datagridview?

I have 4 textboxes in a windows form application and a gridview and button called 'Add'. All I want is, the data entered in 4 textboxes should be gone to the datagridview's four different columns in the same row as i click Add button. If i clear the text boxes, fill them again and click the Add button again then the data should go to the 2nd row of the gridview.
create a class like the following somewhere in your app
public class MyClass
{
public string field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
public string field4 { get; set; }
}
inside your form.cs write this,
public static List<MyClass> lst = new List<MyClass>();
in the click event of your add button do this
private void btnAdd_Click(object sender, EventArgs e)
{
MyClass obj = new MyClass();
obj.field1 = txt1.Text.Trim();
obj.field2 = txt2.Text.Trim();
obj.field3 = txt3.Text.Trim();
obj.field4 = txt4.Text.Trim();
lst.Add(obj);
dataGridView1.DataSource = lst;
}
use this code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Dataset;Integrated Security=True");
SqlDataAdapter ds1 = new SqlDataAdapter();
BindingSource bd = new BindingSource();
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
ds1.InsertCommand = new SqlCommand("INSERT INTO Employee VALUES(#FirstName,#LastName)", con);
ds1.InsertCommand.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
ds1.InsertCommand.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
ds1.InsertCommand.ExecuteNonQuery();
con.Close();
}
private void btndisplay_Click(object sender, EventArgs e)
{
ds1.SelectCommand = new SqlCommand("Select * from Employee", con);
ds.Clear();
ds1.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
bd.DataSource = ds.Tables[0];
//txtFirstName.DataBindings.Add("Text", bd, "FirstName");
//txtLastName.DataBindings.Add("Text", bd, "LastName");
}
private void btnPervious_Click(object sender, EventArgs e)
{
bd.MovePrevious();
update();
records();
}
private void btnNext_Click(object sender, EventArgs e)
{
bd.MoveNext();
update();
records();
}
private void btnFirst_Click(object sender, EventArgs e)
{
bd.MoveFirst();
update();
records();
}
private void btnLast_Click(object sender, EventArgs e)
{
bd.MoveLast();
update();
records();
}
private void update()
{
dataGridView1.ClearSelection();
dataGridView1.Rows[bd.Position].Selected = true;
records();
}
private void records()
{
label1.Text = "records" + bd.Position + " of " + (bd.Count - 1);
}
dont forget to markup this answer
Steps to follow:
1) Upon Binding the DataGrid View, save the DataSource in a Viewstate Variable
2) Define Click event for Add Button
In the click event, recall the Viewstate Variable that has the datasource, Cast it as a DataTable. Make a new row of that datatable, assign values to the cells of the new row. Add this new row to the Datatable, Save the dataTable in ViewSate again, Bind the datasource to the DataGrid
That's All~
Thanks to Mr. SHAKIR SHABBIR first of all, but as i think there is no viewstate in windows form application...
i suggest to use static collection types...
you can define a class for your entry form and foreach textbox a variable, when you click the add button create object of the class, setting all its values with your textboxes, inserting row in grid, and saving all rows data(object of class per gridview row) in a List
you can also use a static datatable... you have to create columns for each of your textfield..
adding row to datatable.. selecting the datasource of your grid...
if you need further help, i am alway here to help you..

Persisting DataTable or GridView DataSource

I have a Click Event that fills a DataTable and the DataTable is the source of my GridView.
Then I have another click event that tries to get the GridView DataSource e converts it back to a DataTable Like:
DataTable dt = (DataTable)GridView1.DataSource;
But the Datasource returns null. Event if I put the code and the Page_Init event waiting for the right postBack
so I would like to know how can i persist the datasource of the gridview, or the DataTable
edited as required:
here is the whole code:
ps: the Page_Init was another try to get the datasource
private DataTable _dataTable;
public DataTable dataTable
{
get { return _dataTable; }
set { _dataTable = value; }
}
protected void Page_Init(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
string ctrlname = BLL.Common.GetPostBackControlId(this.Page);
if(ctrlname == "ButtonDownload")
{
DataTable dt = (DataTable)GridView1.DataSource;
}
}
}
protected void Filter_Click(object sender, EventArgs e)
{
string[] status = new string[2];
status[0] = "Paga";
status[1] = "Disponivél";
dataTable = BLL.PagSeguro.GetTransactions(TextBoxInicio.Text, TextBoxFim.Text, status);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
protected void GetDataSource(object sender, EventArgs e)
{
DataTable dt = (DataTable)GridView1.DataSource;
}
This might work for you.
public partial class Demo : System.Web.UI.Page
{
private DataTable _myData = null;
protected DataTable MyData
{
get
{
if (null == _myData)
{
// You would load your data here.
_myData = new DataTable();
}
return _myData;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Lets say you set your data source here
myGrid.DataSource = this.MyData;
}
protected void Rendering(object sender, EventArgs e)
{
// This is some other event that also needs to get at the data.
DataTable mydata = this.MyData;
}
protected void Unload(object sender, EventArgs e)
{
if (null != _myData)
{
_myData.Dispose();
_myData = null;
}
}
I'm pretty sure you can only access the datasource that way through the DataBound event or ItemDataBound event. You might be able to access the DataRowView for each item in the Items collection, but I'm not sure:
DataRow row = ((DataRowView)GridView1.Rows[0].DataItem).Row;
As for persisting the datasource, you need to consider whether that's a good idea. Your options for storing the datasource are Session or Cache, but if the result set is fairly small it might be more efficient to make another round trip when you need the datasource. Whatever you decide to do, don't store it in ViewState.

Categories