How to bind data column to textbox? - asp.net

I have datagridview and textboxes on form. I load records from different tables when user clicks any one radiobutton. Data in grid is shown perfectly. I want to show values of the row in those textboxes.
One solution can be: binding data from dataset.
Second one can be: transfer values of each cell of row to respective textbox.
Please help me. And, please tell me which one is better or is there any other method which is even better than these two.
Thanks in advance.

Try using a BindingSource
BindingSource bindingSource = new BindingSource();
DataSet dataSet = new DataSet();
DataAdapter da1 = new DataAdapter("Select * from Customers", conn1);
DataAdapter da2 = new DataAdapter("Select * form Orders", conn1);
da1.Fill(dataSet,"Customers");
da2.Fill(dataSet,"Orders");
//Let we set Customers table as bindiningSource datasource
bindingSource.DataSource = dataSet.Tables["Customers"];
private void RadioButtonCustomers_CheckedChanged(object sender, EventArgs e)
{
if(radioButtonCustomers.Checked==true)
bindingSource.DataSource =dataSet.Tables["Customers"];
}
private void RadioButtonOrders_CheckedChanged(object sender, EventArgs e)
{
if(radioButtonOrders.Checked==true)
bindingSource.DataSource = dataSet.Tables["Orders"];
}
//First param of Binding is to which prop of TextBox to bind the value
//Second param is the data source
//Third param is the data member or the column name of the table as datasource, so
//we have to get that table from casting the bindingSource datasource prop and casting it
//to DataTable obj and after that to take the ColumnName prop of the desired column
textBox1.DataBindings.Add(new Binding("Text",bindingSource,((DataTable)bindingSource.DataSource).Columns[0].ColumnName));
textBox2.DataBindings.Add(new Binding("Text",bindingSource,((DataTable)bindingSource.DataSource).Columns[1].ColumnName));
etc...
Even if you change the datasource prop of bindingSource, textboxes will remain binded to rowvalue of first and second column
Hope this help.

Sir I done it making a simple WindowsForm with 2 radio buttons, 2 textboxes and datagridview
here is the sln file http://www13.zippyshare.com/v/98590888/file.html this must help u.

I tried many options to display value in textbox on the same form, but it was not working as datagridview could display records of two different tables.
Instead, I used the following event of datagridview:
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
this.dataGridView1.SelectionChanged += new System.EventHandler(this.DisplayValueinTextBox);
}
In DisplayValueinTextBox, I wrote following code based on numbers of columns displayed for each table:
private void DisplayValueinTextBox(object sender, EventArgs e)
{
try
{
textBox1.Text = dataGridView1.SelectedCells[0].Value.ToString();
textBox2.Text = dataGridView1.SelectedCells[1].Value.ToString();
textBox3.Text = dataGridView1.SelectedCells[2].Value.ToString();
if (tblGrid == "Employee") //name of table which has more columns in grid
{
textBox4.Text = dataGridView1.SelectedCells[3].Value.ToString();
textBox5.Text = dataGridView1.SelectedCells[4].Value.ToString();
textBox6.Text = dataGridView1.SelectedCells[5].Value.ToString();
}
this.dataGridView1.SelectionChanged -= new System.EventHandler(this.DisplayValueinTextBox); //removed it as I was getting error.
}
catch (Exception exdisp)
{
MessageBox.Show(exdisp.Message);
}
}
I also changed SelectionMode property of dataGridView to FullRowSelect. This will ensure that textbox1 is displaying value of SelectedCells[0] even if user clicks any cell.
I still hope there is even a better option, so I wait for comments on this.

Related

How to get the values of the DataSource row that was used to compose another asp:GridView field?

The asp:GridView displays the order lines. It contains only two BoundFields: ID (not visible) and html_text_info (visible). The gvOrderLines.DataSource is explicitly assigned by the DataTable that was obtained by calling the SQL stored procedure. Before that,the html_text_info is added to the DataTable, and it is filled by the formatted HTML text where other columns are the source for the information. See the following method (simplified):
private void LoadGridViewOrderLines()
{
// Get the data table with the order-line data for the order.
DataTable dt = DbUtil.GetAppTable(
"usp_order_lines #order_code=#order_code",
new Hashtable { { "order_code", OrderCode } },
commandTimeoutSeconds: 180);
// Add the field html_text_info, and format the info into it.
dt.Columns.Add("html_text_info", typeof(string));
StringBuilder sb = new StringBuilder();
foreach (DataRow row in dt.Rows)
{
sb.Clear();
// Get the values from the row.
string product_code = row.Field<string>("product_code");
string product_name = row.Field<string>("product_name");
double quantity = ... get the quantity and convert to double...;
string unit = row.Field<string>("unit");
double price = ... get the price and convert to double...;
// Format it as an HTML string.
sb.Append($"{product_code}<br />");
sb.Append($"<b>{product_name}</b><br />");
sb.Append($"Quantity: <b>{quantity:f2} {unit}</b><br />");
sb.Append($"Price: <b>{price:f3}</b><br />");
// Set the formatted value to the field.
row["html_text_info"] = sb.ToString();
}
gvOrderLines.DataSource = dt;
gvOrderLines.DataBind();
}
Now, I want to edit/update the order item. So, I need to access the row from the DataTable that is used as the DataSource. I already have the handler that gets correctly the ID into the property UpdateID (because it was named as DataKeyNames="ID" for the grid view; see below). How can I get the source values that form the composed field?
protected void gvOrderLines_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
{
UpdateID = (int)gvOrderLines.DataKeys[e.NewEditIndex].Value;
// How to get the source values that form the composed field?
tbCode.Text = ???;
tbName.Text = ???;
tbQuantity.Text = ???;
tbPrice.Text = ???;
gvOrderLines.EditIndex = -1; // cancel
gvOrderLines.DataBind();
}
Is the DataRow for current e.NewEditIndex easily accessible? Or do I have to search on my own in the DataTable (that is the gvOrderLines.DataSource)?
The "data row" source ONLY persists during the data binding operations.
So for example, you have "looping" code after you pull the data to on the fly create those extra columns. I often do that, but I still in most cases would suggest you do that "one row" operation in the gv, and not against the table.
This suggestion is not a "must" do, but it can help. Since then you are free to have other buttons, filters or whatever and JUST toss/pass/send/throw to the gv the data source. (so, each time you pull/create/have/use/filter etc. the data source, you don't have to modify it with that extra column.
Thus this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = e.Row.DataItem as DataRowView; // the data source row!!!!
Label Info = (Label)e.Row.FindControl("lblInfo");
StringBuilder sb = new StringBuilder();
sb.Clear();
// Get the values from the row.
string product_code = gData["product_code"].ToString();
string product_name = gData["product_name"].ToString();
double quantity = ... get the quantity and convert to double...;
string unit = gData["unit"].ToString();
double price = ... get the price and convert to double...;
// Format it as an HTML string.
sb.Append($"{product_code}<br />");
sb.Append($"<b>{product_name}</b><br />");
sb.Append($"Quantity: <b>{quantity:f2} {unit}</b><br />");
sb.Append($"Price: <b>{price:f3}</b><br />");
// Set the formatted value to the field.
Info.Text = sb.ToString();
}
}
however, as I stated/noted, the so-called data source (dataitem) that seems to show all over the place in most GV events, is ONLY persisted during the binding process. Once binding is done, then that data item goes out of scope.
Next up, a button click to edit/get the one row.
I (now) in most cases do NOT bother with the gv event model WHEN most of the code and editing is custom code (code you the developer is writing and wanting control of what the heck is going to occur!!!).
So, just drop in a plane jane button into the grid row, and use a plane jane standard button click event.
Say, like this:
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="270" />
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="cmdEdit" runat="server" Text="Edit"
CssClass="btn" OnClick="cmdEdit_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So, note how I do (did not) bother with using the built in gv events.
So, the button click event - a plane jane one looks like this:
protected void cmdEdit_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
Debug.Print("row index click = " + gRow.RowIndex);
Debug.Print("database PK id = " + PKID);
string strSQL = "SELECT * FROM tblHotelsA WHERE ID = " + PKID;
DataRow rstData = MyRst(strSQL).Rows[0];
.. etc. etc.
From that row click, we get/use/have the database PK id, and thus have to re-pull the data. Note how we NEVER exposed/used/have the database PK id in the gv markup - (for reasons of security). (and I see you ALSO using datakeys - good!!).
So, your edit button click (now a plane jane click event) becomes somthing like this:
protected void cmdEdit_Click(object sender, EventArgs e)
{
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
// How to get the source values that form the composed field?
// answer: we re-pull the database row based on pk
int UpdateID = (int)gvOrderLines.DataKeys[e.NewEditIndex].Value;
string strSQL = "SELECT * FROM MyTable WHERE ID = " + UpdateID;
DataRow OneRow = MyRst(strSQL).Rows[0];
// any display value in gv - you use find control ,or cells[] collection
TextBox txtHotelName = gRow.FindControl("txtHotel") as TextBox;
Just remember that dataitem" is available ONLY during binding, and after the databinding to the gv is done, then it (the dataitem) goes out of scope.
If the value(s) you need are not in the gv "display", then you need to re-pull that one row for such values.
templated controls in gv - use find control
built in, use cells[] collection.
Now, to be fair, I don't much use the built in "edit" function, and I just drop in a simple edit button, and either hide the gv, show the hidden edit "div" I have. Or better yet, pop that div like this:

how to pass grid data in a gridview template textbox

I have a grid view name gvwsponsoor and it has 8 cells every cells has template textbox. if i am double click this textbox then open a model popup. i selected this popup data the data is show the textbox. but second rows are not show data, always data show first rows, how to pass all rows show data, please tell me solution any person .
i try to solved this code but not work in this code.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//foreach (GridViewRow grid in gvwSponsor.Rows)
//{
TextBox CostId = (TextBox)gvwSponsor.Rows[0].Cells[2].FindControl("txtCostCenter");
TextBox CostName = (TextBox)gvwSponsor.Rows[0].Cells[1].FindControl("txtDescription");
CostId = (TextBox)gvwSponsor.Rows[0].Cells[2].FindControl("txtCostCenter");
CostName = (TextBox)gvwSponsor.Rows[0].Cells[1].FindControl("txtDescription");
CostId.Text = GridView1.SelectedRow.Cells[2].Text;
CostName.Text = GridView1.SelectedRow.Cells[1].Text;
GridView1.SelectedIndex = -1;
DataTable dtaa = new DataTable();
dtaa = bll.GetNumber(CostId.Text);
if (dtaa.Rows.Count > 0)
{
GridView2.DataSource = dtaa;
GridView2.DataBind();
}
TextBox TxtOp = (TextBox)gvwSponsor.Rows[0].FindControl("txtOP");
TxtOp.Focus();
//}
}
You should process SelectedIndexChanged function of your gridview by using gvwSponsor.SelectedRow, not gvwSponsor.Rows[0]

GridView as DataTable source sorts only for the first time

I implemented sorting on my GridView with a DataTable as DataSource by using code from this MSDN link. However, my grid sorts for the first time when I click any column, and after that it does not sort on clicking any other column.
Code in the PageLoad() event -
if (!Page.IsPostBack)
{
HView hv = new HView ();
DataTable HTable = new DataTable("hTable");
HTable = hv.FillTable();
Session["hTable"] = HTable;
GridView2.DataSource = Session["hTable"];
GridView2.DataBind();
}
Code in the Sorting event -
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable notesDT = Session["hTable"] as DataTable;
if (notesDT != null)
{
notesDT.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortDirection);
GridView2.DataSource = Session["hTable"];
GridView2.DataBind();
}
}
Does anybody have an idea of what I may be doing wrong?
EDIT: I just realized this. If I select a particular row, I have another view that gets populated with details about that row. When I view some rows details first before trying to sort any columns, then sorting works perfectly fine, any number of times. However, if I try to sort before selecting a row, it works only once.
You are using the DataTable as DataSource in the sorting event, but you should use the sorted view instead. Sorting the view won't change the sort order of the data in the table, just the order in the view.
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable notesDT = Session["hTable"] as DataTable;
if (notesDT != null)
{
notesDT.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortDirection);
GridView2.DataSource = notesDT.DefaultView;
GridView2.DataBind();
}
}
Edit: Although that i've just noticed that you're using rhe same code from MSDN.
You could also try to create a new DataTable from the view:
GridView2.DataSource = notesDT.DefaultView.ToTable(true);
You don't need stored the data table into a session. Actually putting the entire data table into session is not a good idea at all. Any particular reason for that?

Making GridView Respond to 2 Drop Down Lists

I have got 2 DropDownLists on my Form and 1 GridView. I want the GridView to display the data according to the selection from the DropDownLists.
For Example, One DropDownList contains Names and another contains Dates. Both the DropDownLists can post back. So if I select a name from 1st DropDownList, the GridView should show all the results according to that Name. Similarly if i select the Date from the other DropDownList , the GridView should show the results according to the dates. But i cant figure out as how to bind GridView to respond to 2 DropDownList.
BTW i am binding both the Drop Down Lists and the Grid View to the DataSource Objects, which is getting data from the database.
Any Suggestions??
It's better and cleaner if You use two DataSource with selecting data from db, and binding each of them to the DropDownList. I tried in my ASP.NET app do what You want but unfortunatelly I have erorrs :/
My only sollution is to don't use DataSouce in aspx file, but in DropDownList SelectedItem event use DataContext and it's possible that then you could bind both to the same DataView like below. I am not sure, but maybe You must use null in DataSource to reset GridView before use new data source:
protected void btPokaz_Click(object sender, EventArgs e)
{
DataClassesDataContext db = new DataClassesDataContext();
var DzieciGrupa = from p in db.Dzieckos
where p.Grupy.Numer == Convert.ToInt32(this.dropListGrupy.SelectedValue)
orderby p.Nazwisko
select new { p.Imie, p.Nazwisko };
if (DzieciGrupa.Count() == 0) this.Label1.Text = "W " + this.dropListGrupy.SelectedValue.ToString() + " grupie nie ma dzieci zapisanych!";
this.GridGrupy.DataSource = null;
this.GridGrupy.DataSource = DzieciGrupa;
// this.GridView1.DataSourceID = String.Empty;
this.GridGrupy.DataBind();
Try it and tell say that works ;)
For Your problem You should create dwo EDM class for each data source. And simple in DDL select event Your choose of DataContext depends from user choose in DDL.
Example :
protected void DDL_SelectedItem(object sender, EventArgs e)
{
TypeOfQueryData query = null;//you must know what type is data You query
if(this.dropListGrupy.SelectedValue==someItemSelect)
{
DataClasses1DataContext db = new DataClasses1DataContext();
//query to get data from source
query= from p in db.Dzieckos
where p.Grupy.Numer == Convert.ToInt32(this.dropListGrupy.SelectedValue)
orderby p.Nazwisko
select new { p.Imie, p.Nazwisko };
}
if(this.dropListGrupy.SelectedValue==otherItemSelect)
{
DataClasses2DataContext db = new DataClasses2DataContext();
query= from p in db.Dzieckos
where p.Grupy.Numer == Convert.ToInt32(this.dropListGrupy.SelectedValue)
orderby p.Nazwisko
select new { p.Imie, p.Nazwisko };
}
this.GridGrupy.DataSource = null;
this.GridGrupy.DataSource = DzieciGrupa;
// this.GridView1.DataSourceID = String.Empty;//maybe You need do that
this.GridGrupy.DataBind();

How do I sort my datagrid?

Editing some legacy code that populates a datagrid entirely in code. I need to order it by two columns but I don't know how. Which event do I hook into and what can I do to order the 2nd and 3rd columns (that contain dates) in order of most recent first?
Edit: Argh it's a datagrid
Datagrid or GridView?
you can create a dataview and sort it (in the constuctor) then bind this back to the grid in the "sorting" event
something like this might be what you're after
protected void myGridView_Sorting(object sender, GridViewSortEventArgs e)
{
// Your data
DataTable dt = new DataTable();
// Create the view
DataView dv = new DataView(dt, "", "COLUMN_TO_SORT", DataViewRowState.CurrentRows);
// Rebind
myGridView.DataSource = dt;
myGridView.DataBind();
}

Resources