Updating textbox based on datagrid view - c#

I have this datagrid view which links to the table answers in the database. The user can edit answers to questions in this form, but I'd like for the textbox to be updated as the button moves onto next answer. This is so the user can edit/delete stuff in the textbox and save it.
private void NextQuestion_Click(object sender, EventArgs e)
{
QuestionsBindingSource.MoveNext();
}
How can I get the textbox to refresh based on selected record in datagridview?

Since you are using a BindingSource, you can get the Current object, cast it to it's type, and get a value.
Let's assume you are bound to a DataTable:
private void NextQuestion_Click(object sender, EventArgs e)
{
if (QuestionsBindingSource != null)
{
QuestionsBindingSource.MoveNext();
if (QuestionsBindingSource.Current != null)
{
DataRow row = (DataRow)QuestionBindingSource.Current;
yourTextBox.Text = row["FieldYouWant"].ToString();
}
}
}
What you cast Current to and the subsequent value reference are both dependent upon what you are bound to (what QuestionsBindingSource is). Adjust this example accordingly.

Related

Get original object from DataRow in GridView C#

I try to display a collection (IEnumerable) of objects (generated via Linq to Sql). Therefore I bind the Gridviews DataSource property to the generated output of my Linq to SQL method. In the SelectedIndexChanged event of the GridView I try to convert the selected rows DataItem back to my original object but end up with a null value instead.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
RlDataContext dc = new RlDataContext();
this.dgvReports.DataSource = dc.GetReports(1);
this.dgvReports.DataBind();
}
protected void dgvReports_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.dgvReports.SelectedIndex >= 0)
{
Report rpt = (Report)this.dgvReports.SelectedRow.DataItem;
}
}
The return type of GetReports is ISingleResult<Report>
Use a bindingsource between your datagridview and your list. When a selection is made is datagridview use the bindingsource's Current property to get you the right item from the list.
This is how I always get my information from a datagridview
string variabel = yourDataGridView["Columnname"].ToString();
You can also use this in a loop then it will be:
string variabel = yourDataGridView["RowNumber"].Cells["Columnname"].Value.ToString();
I hope this helps!

How to Update ONLY the Gridview in C#

I have gridview in my C# ASP.net application.
When a user edits a row, all I want to do is update the gridview's datasource (Not the database yet, since I'm just taking the datagrid's datasource at the end and pushing it into my database as a dataset).
But The values I get are the old values, not the updated values im editing on the gridview.
Why is this happening? I'm following all the advice on these links.
protected void grdViewDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)grdViewDetails.Rows[e.RowIndex];
int adsf = row.Controls.Count;
foreach (Control item in row.Controls)
{
if (item.Controls[0] is TextBox)
{
TextBox textbox = (TextBox)item.Controls[0];
string x = textbox.Text;
//on the second for loop the string variable x = Employee1
}
if (item.Controls[0] is Label)
{
Label mylabel = (Label)item;
//do stuff
}
Now that textbox variable x should be xxxxxxx, but its still the old value.... why does this happen?
Cant you just update the gridview WITHOUT updating any other datasets/sources. Since I use the whole datasource of the gridview at the end.
You can access the new values with the GridViewUpdateEventArgs. Here's an example from the documentation:
void CustomersGridView_RowUpdating(Object sender, GridViewUpdateEventArgs e)
{
// Iterate through the NewValues collection and HTML encode all
// user-provided values before updating the data source.
foreach (DictionaryEntry entry in e.NewValues)
{
e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());
}
}
You can use the debugger to inspect your e variable more closely and find out which values do you need.

How to get Current Row Index by selecting anywhere in gridview withour Select command

I need to find a RowIndex of the current row by selecting anywhere on the Gridview without SelectCommand. Basically i need it because i am creating a method which will return the Object depending on the DataKey of the SelectedRow. And i am calling it everywhere on the Page and i do not want to write the same code again an again.
Here is what i have.
On RowDataBound
protected void gvOrders_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var dataKey = gvOrders.DataKeys[e.Row.RowIndex];
if (dataKey == null)
return;
int orderId = AlwaysConvert.ToInt(dataKey["OrderId"]);
Order cncOrder = OrderDataSource.Load(orderId);
// do some work
}
}
Now i have a 3 CheckBox column in gridview, so whenever i check the CheckBox state i am doing the following and load the Object again and do some database work.
On CheckBox Change Event
protected void cbIsReceived_CheckedChanged(object sender, EventArgs e)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
var dataKey = gvOrders.DataKeys[row.RowIndex];
if (dataKey == null)
return null;
int orderId = AlwaysConvert.ToInt(dataKey["OrderId"]);
Order cncOrder = OrderDataSource.Load(orderId);
// find the controls using the current row index
CheckBox cbIsReceived = (CheckBox)gvOrders.Rows[row.RowIndex].FindControl("cbIsReceived");
Label receivedDateText = (Label)gvOrders.Rows[row.RowIndex].FindControl("receivedDateText");
// do some work
}
As you can see in both events most of the code is to find the current RowIndex and load the Object and then do some database work.
if you notice, in both event the arguments supplied is different i.e OnRowBound its (GridViewRowEventArgs e) and OnCheckBox_CheckedChanged its (EventArgs e).
So for every CheckBox column i have to write the same code again and again.
I would like to create method where i can pass the Sender and get the current RowIndex back. I am not sure how to do that. please help.
You can route the events from all 3 CheckBoxes to the same method by either:
Just supply cbIsReceived_CheckedChanged as the event handler for
all three checkboxes OR:
If you've already generated methods to handle the events for all
the other CheckBoxes, then do this for all the auto-generated methods:
cbAnotherCheckBox_CheckedChanged(Object sender, EventArgs e)
{
// call the first method you've already written:
cbIsReceived_CheckedChanged(sender, e);
}
Edit:
If there are different operations for each of the CheckBoxes, then loop through the rows to get the particular CheckBox that was checked and then run the operation that's specific to it.

adding new row to datagrid view programmatically

I Have a datagridview that gets data from database and shows to the user,I also have three textboxes through which user can enter the value into the datagrid view if I select an already existing row in the datgrid and then enter value by text boxes it makes the changes and when I push change button changes are made successfully in both db and the datagridview
but if I select an empty row in the datagrid view and try to enter the values I cannot new row is not added to the datagrid view although allow user to add new row is set to true.
private void txtName_TextChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
dataGridView1.SelectedRows[0].Cells["Name"].Value = txtName.Text;
}
}
private void txtRelation_TextChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
dataGridView1.SelectedRows[0].Cells["Relation"].Value = txtRelation.Text;
}
}
private void txtID_TextChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
dataGridView1.SelectedRows[0].Cells["ID"].Value = txtID.Text;
}
}
Check if your gridview is readonly. If Readonly is true then set it to false to enable user add new row. Another reason might be the "EditMode" property of DataGridView. It should not be "Edit Programatically" if you want to allow user to add new row
You have to double click a row to actually create a new row. However, if you do not want the stress of double clicking, you could make the row select event to perform a click on the row.

ASP.Net: GridView control and combobox woes

I've got a GridView control and Combobox control that are both successfully populated in my Page_Load event (within a block that checks for IsPostBack == false).
I've got an empty button 'btnClick' event handler which will reload the page when clicked. Both the GridView and Combobox controls have their EnableViewState property set to True. The behaviour I was expecting and hoping for was:
Page will reload with the GridView control still populated.
Page will reload with Combobox still populated and the item selected by the user still set as the selected item.
Unfortunately, the behaviour I'm getting is as follows:
GridView control is now empty and shows no data.
Combobox is now empty.
Code as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
DataAccessObj daObj = new DataAccessObj();
foreach (DataRow dataRow in daObj.GetAllData())
{
ListItem listItem = new ListItem(dataRow.ToString(), dataRow.Id.ToString());
myCombobox.Items.Add(listItem);
}
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Do nothing
}
What I would like to do is allow the user to select an item from the Combobox. Upon clicking Submit, the GridView would be repopulated (based upon the selected item). The Combobox will remain populated and show the last selected item.
Can someone help explain where I might be going wrong? TIA
When you click your button, the page is posted back, in your page load, if it is a postback you need to databind the grid appropriately you need to add a condition to your page load event like
Firstly on your btn_click, you need to store the id selected with something like:
if (myCombobox.SelectedItem != null)
{
if (int.TryParse(myCombobox.SelectedItem.Value, out reportedById) == false)
{
reportedById = 0;
ViewState["reportedById"] = reportedById; // Need to remember which one was selected
}
}
Then On your Post Back
else (IsPostBack)
{
if (ViewState["reportedById"]) != null)
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(Convert.ToInt32(ViewState["reportedById"]));
IncidentGrid.DataBind();
myCombobox.SelectedItem.Value = ViewState["reportedById"].ToString(); // set combo
}
else
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}

Categories