Create session in gridview cell - c#

i have a gridview with tempaltefield buttons,
i want to create a session with value of a cell in selected button row ,
can anyone help me i tryed this but didnt work:
protected void ImageButton1_Click1(object sender, ImageClickEventArgs e)
{
Session["mysession"] = GridView1.SelectedRow.Cells[1].Text;
}

First of all, if it's just a imagebutton in a templatefield, actually you don't select de row. This line will problably throw an exception because SelectedRow is null.
But if you are using a command to select, that's correct. Maybe your event (ImageButton1_Click1) is not assigned to your image (OnClick).
You can try something like this:
protected void Page_Load(object sender, EventArgs e)
{
try
{
//Add and event RowDataBound
grvGrid.RowDataBound += new GridViewRowEventHandler(grvGrid_RowDataBound);
}
catch
{
//...throw
}
}
protected void grvGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.Header)
{
//...
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Add an ImageButton foreach row in GridView
ImageButton ibtImageAlt = new ImageButton();
ibtImageAlt.ImageUrl = "App_Images/y.gif";
//ImageButton's ID will be the index of the row
ibtImageAlt.ID = e.Row.RowIndex.ToString();
ibtImageAlt.ForeColor = System.Drawing.Color.White;
ibtImageAlt.Font.Overline = false;
ibtImageAlt.Click += ibtImageAlt_Click;
}
}
catch
{
//...throw
}
}
protected void ibtImageAlt_Click(object sender, EventArgs e)
{
try
{
//Catch the ImageButton ID and the row in GridView
//An example to catch the value of the row selected by the ImageButton
Int32 intIndexRow = Convert.ToInt32(((ImageButton)sender).ID);
String strTest = grvGrid.Rows[intIndexRow].Cells[0].Text;
}
catch
{
//...throw
}
}

Related

How to display paragraph like content in DataGridView?

I am trying to develop an simple "Invoice" Windows application. I have bounded the textboxes (Item, Description, MRP, Quantity, etc.) to DataGridView but data entered by user in the "Description" textbox (multiline) has to be displayed as it is in GridView which is not happening in my code.
My code:
private void DS_Invoice_Load(object sender, EventArgs e)
{
this.allDataTableAdapter.Fill(this.database1DataSet4.AllData);
this.itemDataTableAdapter.Fill(this.database1DataSet3.ItemData);
this.custDataTableAdapter.Fill(this.database1DataSet2.CustData);
groupBox1.Enabled = false;
groupBox2.Hide();
groupBox3.Show();
groupBox3.Enabled = true;
max();
tb_inv_id.ReadOnly = true;
tb_order_id.Text = "-";
tb_net_amt.Text = "0";
tb_amt.Text = "0";
}
private void btnAddJob_Click(object sender, EventArgs e)
{
if (dataGridView1.Columns.Count == 0)
{
dataGridView1.Columns.Add("Item Name", "Name");
dataGridView1.Columns.Add("Description", "Description");
dataGridView1.Columns.Add("Qauntity", "Qauntity");
dataGridView1.Columns.Add("Rate", "Rate");
dataGridView1.Columns.Add("Amount", "Amount");
}
// Add the text box values to a new row in the DataGridView
dataGridView1.Rows.Add(new object[] { tbItemNm.Text, tbItemDscr.Text,
tb_quantity.Text,tb_rate.Text,tb_amt.Text});
MessageBox.Show("Item Added successfully..", "Add Job", MessageBoxButtons.OK);
tbItemNm.Clear();
tbItemDscr.Clear();
tb_quantity.Clear();
tb_rate.Clear();
tb_amt.Clear();
tbItemNm.Focus();
}
Try this example for wrapping text in grid view.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("style", "word-break:break-all;word-wrap:break-word;width:100px");
}
}
}

ASP.NET GridView does not update its row

I followed this tutorial on MSDN for ASP.NET GridView Update Row, but it does not work.
updatedItem.DepartureCity = ((TextBox)(row.Cells[2].Controls[0])).Text;
Still gives the original value from the cell and not the updated one.
public partial class ManagePage : System.Web.UI.Page
{
BusScheduleModelContainer modelContainer = new BusScheduleModelContainer();
protected void Page_Load(object sender, EventArgs e)
{
//FormsAuthentication.RedirectFromLoginPage()
//if (!HttpContext.Current.User.Identity.IsAuthenticated)
//{
// Server.Transfer("LoginPage.aspx");
//}
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
}
protected void RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var routeID = int.Parse(e.Values[0].ToString());
var removedItem = modelContainer.BusRoutes.FirstOrDefault(
item => item.RouteID == routeID);
if (removedItem != null)
{
modelContainer.BusRoutes.Remove(removedItem);
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
modelContainer.SaveChanges();
}
}
protected void RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var routeID = int.Parse(e.NewValues[0].ToString());
var updatedItem = modelContainer.BusRoutes.FirstOrDefault(
item => item.RouteID == routeID);
if (updatedItem != null)
{
GridViewRow row = resultsGridView.Rows[e.RowIndex];
var res = row.FindControl("ctl00$ContentPlaceHolder1$resultsGridView$ctl02$ctl03");
updatedItem.DepartureCity = ((TextBox)(row.Cells[2].Controls[0])).Text;
updatedItem.ArrivalCity = ((TextBox)(row.Cells[3].Controls[0])).Text;
updatedItem.DepartureTime = DateTime.Parse(((TextBox)(row.Cells[4].Controls[0])).Text);
updatedItem.ArrivalTime = DateTime.Parse(((TextBox)(row.Cells[5].Controls[0])).Text);
}
resultsGridView.EditIndex = -1;
BindData();
}
protected void RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
resultsGridView.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindData();
}
protected void RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
resultsGridView.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
private void BindData()
{
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
}
}
<div>
<asp:GridView runat="server" ID="resultsGridView"
AutoGenerateColumns="true" AllowPaging="true"
AutoGenerateDeleteButton="true" OnRowDeleting="RowDeleting"
AutoGenerateEditButton="true" OnRowUpdating="RowUpdating"
OnRowEditing="RowEditing" OnRowCancelingEdit="RowCancelingEdit">
</asp:GridView>
</div>
Do you use CommandField for update controler?
If so, when you click update button, first it will do Page_Load event handler, after that do the implementation in RowUpdating event handler.
You should try to check post back in Page_Load event handler like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
}
}
By this way, it will bind data to the GridView only first time you open this page.
For post back event such as clicking update button, it will not bind the original data to GridView again.
In RowUpdating method you need to add modelContainer.SaveChanges(); like below:
if (updatedItem != null)
{
GridViewRow row = resultsGridView.Rows[e.RowIndex];
var res = row.FindControl("ctl00$ContentPlaceHolder1$resultsGridView$ctl02$ctl03");
updatedItem.DepartureCity = ((TextBox)(row.Cells[2].Controls[0])).Text;
updatedItem.ArrivalCity = ((TextBox)(row.Cells[3].Controls[0])).Text;
updatedItem.DepartureTime = DateTime.Parse(((TextBox)(row.Cells[4].Controls[0])).Text);
updatedItem.ArrivalTime = DateTime.Parse(((TextBox)(row.Cells[5].Controls[0])).Text);
modelContainer.SaveChanges();
}

Delete row from objectdatasource before binding to gridview

I have some data in ObjectDataSource, before binding the data to the GridView, I want to remove some rows from the DataSource.
This is what I am trying:
protected void gvExitInterview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
User employee = (User) e.Row.DataItem;
if(//some condition here)
{
//do nothing
}
else
{
//delete the row
this.gv.DeleteRow(e.Row.RowIndex);
return;
}
}
}
These are my deletion methods:
protected void gvExitInterview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void gvExitInterview_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
gv.DataBind();
}
This is my grid binding:
private void BuildGrid(DateTime from, DateTime to)
{
this.objDS.TypeName = "EmployeeManagement";
this.objDS.SelectMethod = "GetEmployees";
this.objDS.SelectCountMethod = "GetEmployeesCount";
this.objDS.SelectParameters.Clear();
this.objDS.SelectParameters.Add("from", from.ToString());
this.objDS.SelectParameters.Add("to", to.ToString());
this.objDS.SelectParameters.Add("csvEntities", csv);
this.objDS.SelectParameters.Add("sortExpression", ViewState["SortColumn"].ToString());
this.gv.DataSource = objDS;
this.gv.DataBind();
}
This is not working, it does not filter or delete any data from the grid. Any idea how to do explicit deletion?
I think you need to write another SelectMethod in the DataObjectClass which get a parameter which you use pass to filter condition. So that just returning with the rows required to display.

c# ItemDataBound new event handler

protected virtual void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
this.list = (DropDownList)e.Item.FindControl("edit_list");
if (list != null)
{
list.SelectedIndexChanged += new EventHandler(List_SelectedIndexChanged);
}
}
List is assigned, but selectedIndex eventHandler won't work
if i make RepairsStateList.BackColor = Color.Black; it is working
protected void List_SelectedIndexChanged(object source, System.EventArgs e)
{
Response.Write("<script>alert('vv') </script>");
}
AutoPostBack property of this dropdown must be set to true...
than you code must be
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e) {
// get reference to the row
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
// Get the reference of this DropDownlist
DropDownList dropdownlist1 = (DropDownList) gvr.FindControl("dropdownlist1");
}
Edit
Replace this line with
this.list = (DropDownList)e.Item.FindControl("edit_list");
this
DropDownList list = (DropDownList)e.Item.FindControl("edit_list");
if (list != null)
{
list.SelectedIndexChanged += new EventHandler(List_SelectedIndexChanged);
}

Retrieving values of dynamically created controls on Post back in Asp.Net

I need to dynamically add CheckBoxList on the SelectedIndexChanged event of DropDownList. I have achieved this but I cannot retain its value on postback.
Here’s what I have done so far:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
loadTracks();//Needs to generated dynamically
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadDegrees();
}
loadTracks();
}
public void loadTracks()
{
try
{
ConfigurationDB objConfig = new ConfigurationDB();
DataSet ds = objConfig.GetTracksByDegreeID(
Convert.ToInt32(ddlDegree.SelectedValue.ToString()));
CheckBoxList CbxList = new CheckBoxList();
CbxList.ID = "Cbx";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
CbxList.Items.Add(new ListItem(ds.Tables[0].Rows[i]["Track_Name"]
.ToString(), ds.Tables[0].Rows[i]["ID"].ToString()));
}
ph.Controls.Add(CbxList);
ViewState["tracks"] = true;
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
//For testing, I added a button and on its click I have added this code
protected void btnDetails_Click(object sender, EventArgs e)
{
CheckBoxList Cbx = (CheckBoxList)ph.FindControl("chk");
foreach (ListItem ex in Cbx.Items)
{
if (ex.Selected)
{
Response.Write(String.Format("You selected: <i>{0}</i> <br>", ex.Value));
}
}
}
Might be a typo:
CbxList.ID = "Cbx";
v.s.
CheckBoxList Cbx = (CheckBoxList)ph.FindControl("chk");
You can try it without changing the code and use pre PreRender
just run you loadTracks()

Categories