datagridview in asp.net retrieve value - asp.net

i am working on visual stdio 2008 and my database is in sql server 2005
MY table has three columns
1. SenderName
2. RecieverName
3. Message
i have displayed this table in GridView and add a button named as Reply
so my grid view look's some what like this
SenderName|RecieverName| MessAge|REPLY BUTTON
now this what i want to do
when Button is Clicked in My gridView i need to get data of that specific row
i.e Sender's NAme so that i can Reply him/her ?
can any one help????

Here's a sample:
Markup:
<asp:GridView
runat="server"
ID="gvEmails"
OnSelectedIndexChanged="gvEmails_SelectedIndexChanged">
<Columns>
<asp:ButtonField CommandName="Select" ButtonType="Button" Text="Send" />
</Columns>
</asp:GridView>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("SenderName");
dt.Columns.Add("ReceiverName");
dt.Columns.Add("Message");
DataRow dr;
dr = dt.NewRow();
dr["SenderName"] = "John Doe";
dr["ReceiverName"] = "Jane Doe";
dr["Message"] = "Hi, Jane.";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["SenderName"] = "Michelle Smith";
dr["ReceiverName"] = "Mike Smith";
dr["Message"] = "Yo, Mike.";
dt.Rows.Add(dr);
gvEmails.DataSource = dt;
gvEmails.DataBind();
}
protected void gvEmails_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = gvEmails.SelectedRow;
Response.Write("Send email to " + row.Cells[1].Text);
}

there is a selected index changed function in the properties.
Captuer the selected index and get the cell value of that selected index.
Then continue whtever u want.

There are many different ways of doing this. The easiest, if you only need a single value, would be to bind the value to the CommandArgument of your Reply button. Then add an OnClick handler to your button. Then in the OnClick method you can get the name from the CommandArgument.
If you need more than a single value from the row, you will need to do a little more work. You can setup an event handler on the GridView to capture the event of the index changing. This will provide some event arguments that has a NewSelectedIndex. That will tell you what row was selected. Depending on how your data is bound to your GridView, you can access the data again to get the values you need, or you can set the columns to be a DataKey in the GridView and access them that way.

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 get the selected row index and that selected row's cell value using delete button

I have use the templete field delete button in gridview, so when I click on any delete button in the gridview to delete a row at that time it will give the deleting row index with that selected row's cells[0] value. How can I do any one have a idea....?
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
int grdid = Int32.Parse(GridView3.Rows[index].Cells[0].Text);
IndiesProductDataContext ip = new IndiesProductDataContext();
ip.iLinks.DeleteAllOnSubmit(ip.iLinks.Where(c => c.ProductID == grdid));
ip.SubmitChanges();
}
I am using row command in gridview deleting row geting index but it does not work
You can set CommandArgument property of button
In Aspx:
<asp:Button ID="btnDeleteContact" CommandName="DeleteContact"
CommandArgument="<%# Eval("ContactID") %>" runat="server" >Delete</asp:Button>
In _RowCommand event of GridView:
If e.CommandName = "DeleteContact" Then
Dim objContacts As New CContacts
objContacts.ContactID = e.CommandArgument
objContacts.DomainID = Session("DomainID")
Dim strError As String = objContacts.DelContact()
End If
hope it helps
You can not do it in that way but you will have to use buttons click event to select the ID and then use that ID as perameter for second, different delete query.
i found The perfect solution of this problem...
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
int ci = Int32.Parse(GridView3.Rows[RowIndex].Cells[1].Text);
ProductDataContext ip = new ProductDataContext();
ip.iLinks.DeleteAllOnSubmit(ip.iLinks.Where(c => c.PID == ci));
ip.SubmitChanges();
}
this code worked properly in my module...

GridView Paging Issue

I am using a gridview control and performing Paging and Sorting manually.
Here is the method of Paging:
protected void gdvMainList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gdvMainList.PageIndex = e.NewPageIndex;
gdvMainList.DataSource = dtConsentReleaseList;
gdvMainList.DataBind();
}
I have a static datatable having a column Id:
dtConsentReleaseList.Columns.Add("Id");
dtConsentReleaseList.Columns.Add("StartDate");
dtConsentReleaseList.Columns.Add("EndDate");
dtConsentReleaseList.Columns.Add("Contact");
I am assigning datakeynames "Id" in my GridView.
And I also have a print button in each row. When I click that button, this code gets executed:
else if (e.CommandName == "New")
{
int selectedIndex = Convert.ToInt32(e.CommandArgument);
int consentReleaseId = Convert.ToInt32(gdvMainList.DataKeys[selectedIndex].Value);
string openReportScript = Utility.OpenReport(ResolveClientUrl("~/Reports/Consumer/ConsentReleaseReport.aspx?Id=" + consentReleaseId + "&ReportTitle=ConsentForRelease"));
ScriptManager.RegisterClientScriptBlock(upConsentRelease, upConsentRelease.GetType(), "Pop up", openReportScript, true);
}
but when I change the page and clicks print button, an exception occurs on this line :
int consentReleaseId = Convert.ToInt32(gdvMainList.DataKeys[selectedIndex].Value);
Exception is:
Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index
I guess I am doing something wrong in Paging method.
Any help please?
You are trying to get a value out of an array based on an arbitrary ID instead of the actual index. But you don't need to do that at all. You don't need to store your ID in the DataKeys and you don't need to access anything using the index of the item. Just pull your ID out from the CommandArgument.
<asp:ImageButton CommandName="New" CommandArgument='<%# Eval("Id") %>' ID="ibtnPrint" runat="server" ImageUrl="~/App_Themes/Default/images/print.png" />
And then in code-behind:
int consentReleaseId = int.Parse(e.CommandArgument);
My guess is that you bind the gridview in code-behind (possibly page_load event) and it doesn't hold the values on postback.
Also, try to pass the Id as CommandArgument. As far as I can tell, if you have access to Id of the selected record, you don't need grid's row index at all. (GridView passes row's index as CommandArgument by default)
Set the datakeyname right before you set the datasource and bind the gridview.
In addition,
string[] dk = new string[1] {"MyID"};
myGridView.DataKeyNames = dk;
myGridView.DataSource = ds;
myGridView.DataBind();

How to hide columns in an ASP.NET GridView with auto-generated columns?

GridView1.Columns.Count is always zero even SqlDataSource1.DataBind();
But Grid is ok
I can do
for (int i = 0; i < GridView1.HeaderRow.Cells.Count;i++)
I rename request headers here
but
GridView1.Columns[i].Visible = false;
I can't use it because of GridView1.Columns.Count is 0.
So how can I hide them ?
Try putting the e.Row.Cells[0].Visible = false; inside the RowCreated event of your grid.
protected void bla_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false; // hides the first column
}
This way it auto-hides the whole column.
You don't have access to the generated columns through grid.Columns[i] in your gridview's DataBound event.
The Columns collection is only populated when AutoGenerateColumns=false, and you manually generate the columns yourself.
A nice work-around for this is to dynamically populate the Columns collection yourself, before setting the DataSource property and calling DataBind().
I have a function that manually adds the columns based on the contents of the DataTable that I want to display. Once I have done that (and then set the DataSource and called DataBind(), I can use the Columns collection and the Count value is correct, and I can turn the column visibility on and off as I initially wanted to.
static void AddColumnsToGridView(GridView gv, DataTable table)
{
foreach (DataColumn column in table.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName;
gv.Columns.Add(field);
}
}
Note: This solution only works if your GridView columns are known ahead of time.
It sounds like you're using a GridView with AutoGenerateColumns=true, which is the default. I recommend setting AutoGenerateColumns=false and adding the columns manually:
<asp:GridView runat="server" ID="MyGridView"
AutoGenerateColumns="false" DataSourceID="MySqlDataSource">
<Columns>
<asp:BoundField DataField="Column1" />
<asp:BoundField DataField="Column2" />
<asp:BoundField DataField="Column3" />
</Columns>
</asp:GridView>
And only include a BoundField for each field that you want to be displayed. This will give you the most flexibility in terms of how the data gets displayed.
I was having the same problem - need my GridView control's AutogenerateColumns to be 'true', due to it being bound by a SQL datasource, and thus I needed to hide some columns which must not be displayed in the GridView control.
The way to accomplish this is to add some code to your GridView's '_RowDataBound' event, such as this (let's assume your GridView's ID is = 'MyGridView'):
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[<index_of_cell>].Visible = false;
}
}
That'll do the trick just fine ;-)
You have to perform the GridView1.Columns[i].Visible = false; after the grid has been databound.
Try this to hide columns in an ASP.NET GridView with auto-generated columns, both RowDataBound/RowCreated work too.
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Or _
e.Row.RowType = DataControlRowType.Header Then // apply to datarow and header
e.Row.Cells(e.Row.Cells.Count - 1).Visible = False // last column
e.Row.Cells(0).Visible = False // first column
End If
End Sub
Protected Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowCreated
If e.Row.RowType = DataControlRowType.DataRow Or _
e.Row.RowType = DataControlRowType.Header Then
e.Row.Cells(e.Row.Cells.Count - 1).Visible = False
e.Row.Cells(0).Visible = False
End If
End Sub
In the rowdatabound method for 2nd column
GridView gv = (sender as GridView);
gv.HeaderRow.Cells[2].Visible = false;
e.Row.Cells[2].Visible = false;
#nCdy:
index_of_cell should be replaced by an integer, corresponding to the index number of the cell that you wish to hide in the .Cells collection.
For example, suppose that your GridView presents the following columns:
CONTACT NAME | CONTACT NUMBER | CUSTOMERID | ADDRESS LINE 1 | POST CODE
And you want the CUSTOMERID column not to be displayed.
Since collections indexes are 0-based, your CUSTOMERID column's index is..........? That's right, 2!! Very good.
Now... guess what you should put in there, to replace 'index_of_cell'??
As said by others, RowDataBound or RowCreated event should work but if you want to avoid events declaration and put the whole code just below DataBind function call, you can do the following:
GridView1.DataBind()
If GridView1.Rows.Count > 0 Then
GridView1.HeaderRow.Cells(0).Visible = False
For i As Integer = 0 To GridView1.Rows.Count - 1
GridView1.Rows(i).Cells(0).Visible = False
Next
End If
I found Steve Hibbert's response to be very helpful. The problem the OP seemed to be describing is that of an AutoGeneratedColumns on a GridView.
In this instance you can set which columns will be "visible" and which will be hidden when you bind a data table in the code behind.
For example:
A Gridview is on the page as follows.
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" >
</asp:GridView>
And then in the code behind a PopulateGridView routine is called during the page load event.
protected void PopulateGridView()
{
DataTable dt = GetDataSource();
gv.DataSource = dt;
foreach (DataColumn col in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = col.ColumnName;
field.HeaderText = col.ColumnName;
if (col.ColumnName.EndsWith("ID"))
{
field.Visible = false;
}
gv.Columns.Add(field);
}
gv.DataBind();
}
In the above the GridView AutoGenerateColumns is set to False and the codebehind is used to create the bound fields. One is obtaining the datasource as a datatable through one's own process which here I labeled GetDataSource(). Then one loops through the columns collection of the datatable. If the column name meets a given criteria, you can set the bound field visible property accordingly. Then you bind the data to the gridview. This is very similar to AutoGenerateColumns="True" but you get to have criteria for the columns. This approach is most useful when the criteria for hiding and un-hiding is based upon the column name.
Similar to accepted answer but allows use of ColumnNames and binds to RowDataBound().
Dictionary<string, int> _headerIndiciesForAbcGridView = null;
protected void abcGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (_headerIndiciesForAbcGridView == null) // builds once per http request
{
int index = 0;
_headerIndiciesForAbcGridView = ((Table)((GridView)sender).Controls[0]).Rows[0].Cells
.Cast<TableCell>()
.ToDictionary(c => c.Text, c => index++);
}
e.Row.Cells[_headerIndiciesForAbcGridView["theColumnName"]].Visible = false;
}
Not sure if it works with RowCreated().
Iterate through the GridView rows and make the cells of your target columns invisible. In this example I want to keeps columns 4-6 visible as is, so we skip those:
foreach (GridViewRow row in yourGridView.Rows)
{
for (int i = 0; i < rows.Cells.Count; i++)
{
switch (i)
{
case 4:
case 5:
case 6:
continue;
}
row.Cells[i].Visible = false;
};
};
Then you will need to remove the column headers separately (keep in mind that removing header cells changes the length of the GridView after each removal):
grdReportRole.HeaderRow.Cells.RemoveAt(0);

Getting Row's Name in a DataList

I have a datalist and would like to pull the row names from the table that I am getting my values from for the datalist. Heres an example of what I would like to do.
<HeaderTemplate>
'Get data row names
'Maybe something like Container.DataItem(row)?
</HeaderTemplate>
If you are using a DataTable as a Data Source for your Data List you could use the OnItemCreated method and provide a custom handler for the ItemCreated event to add the column header values. I'm not sure why you would want to do this. It sounds like a Repeater or GridView might be better suited to your needs. At any rate, here's the code.
<asp:DataList ID="DataList1" runat="server" OnItemCreated="DataList1_ItemCreated"
ShowHeader="true" >
<HeaderTemplate>
</HeaderTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT [id], [name], [email], [street], [city] FROM [employee_tbl]", conn);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
foreach (DataColumn col in dt.Columns)
{
Literal lit = new Literal();
lit.Text = col.ColumnName;
e.Item.Controls.Add(lit);
}
}
}
You could do the following, but I doubt it would work. I don't believe DataItems are available at the point when the Header is being created.
((DataRowView)Container.DataItem).DataView.Table.Columns
If this works, you can loop through this collection and inspect each item's ColumnName property.
A better idea would be to either:
Create a property in codebehind that returns a List<string> of appropriate column headers. You can refer to this property in markup when you're declaring the header.
Add a handler for the ItemDataBound event and trap header creation. You will still need a way to refer to the data elements, which probably haven't been prepped at this point.

Resources