Unable to check all check boxes in a GridView - c#

I am using grid view check box to select all the values in the grid view when i click the check box, but the problem i am facing is it is selecting the only the first page value how ever i have coded to bring all the values in but in design it is not working out
this is the image
i want all the check box to checked in design when i press the all check button.
protected void gvBatch_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType != DataControlRowType.Header && e.Row.RowType != DataControlRowType.Footer && e.Row.RowType != DataControlRowType.Pager)
{
DropDownList ddlcountry1 = (DropDownList)e.Row.FindControl("ddlcountry");
populateLocationValues(ddlcountry1);
{
ArrayList checkboxvalues = (ArrayList)Session["BP_PrdId"];
//string Bp_Id = "";
if (checkboxvalues != null && checkboxvalues.Count > 0)
{
string strBp_Id = ((HiddenField)e.Row.FindControl("hf_ProductLblId")).Value.ToString();
if (checkboxvalues.Contains(strBp_Id))
{
CheckBox myCheckBox = (CheckBox)e.Row.FindControl("chkPLPSltItem");
myCheckBox.Checked = true;
}
}
}
DataSet dsaccess = MenuRestriction();
DataRow dr = null;
string sView = "";
string sEdit = "";
string sInsert = "";
string sDeactive = "";
if (dsaccess.Tables.Count > 0)
{
if (dsaccess.Tables[0].Rows.Count > 0)
{
dr = dsaccess.Tables[0].Rows[0];
sView = dr["MnuRgts_View"].ToString();
sEdit = dr["MnuRgts_Edit"].ToString();
sInsert = dr["MnuRgts_Insert"].ToString();
sDeactive = dr["MnuRgts_DeActivate"].ToString();
if (sInsert == "Y" && sDeactive == "Y")
{
BtnDelete.Visible = true;
imgNew.Visible = true;
}
else
{
BtnDelete.Visible = false;
imgNew.Visible = false;
if (sInsert == "Y")
{
imgNew.Visible = true;
}
if (sDeactive == "Y")
{
BtnDelete.Visible = true;
}
}
}
}
}
}
catch (Exception ex)
{
log.Error("gvBatch_RowDataBound", ex);
}
}
protected void gvBatch_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
RememberOldValues();
gvBatch.PageIndex = e.NewPageIndex;
//RetrieveValues();
BindGrid();
LoadLocation();
//RePopulateValues();
}
private void RememberOldValues()
{
ArrayList checkboxvalues = new ArrayList();
string strBp_Id = "";
foreach (GridViewRow row in gvBatch.Rows)
{
//index = (int)gvBatch.DataKeys[row.RowIndex].Value;
strBp_Id = ((HiddenField)row.FindControl("hf_ProductLblId")).Value.ToString();
bool result = ((CheckBox)row.FindControl("chkPLPSltItem")).Checked;
// Check in the Session
if (Session["BP_PrdId"] != null)
checkboxvalues = (ArrayList)Session["BP_PrdId"];
if (result)
{
if (!checkboxvalues.Contains(strBp_Id))
checkboxvalues.Add(strBp_Id);
}
else
{
if (checkboxvalues.Contains(strBp_Id))
checkboxvalues.Remove(strBp_Id);
}
}
if (checkboxvalues != null && checkboxvalues.Count > 0)
Session["BP_PrdId"] = checkboxvalues;
}
protected void gvBatch_PreRender(object sender, EventArgs e)
{
try
{
if (gvBatch.TopPagerRow != null)
{
((Label)gvBatch.TopPagerRow.FindControl("lbCurrentPage")).Text = (gvBatch.PageIndex + 1).ToString();
((Label)gvBatch.TopPagerRow.FindControl("lbTotalPages")).Text = gvBatch.PageCount.ToString();
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnFirst")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnPrev")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnNext")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnLast")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
DropDownList ddlist = (DropDownList)gvBatch.TopPagerRow.FindControl("ddlPageItems");
ddlist.SelectedIndex = ddlist.Items.IndexOf(ddlist.Items.FindByValue(ViewState["DropDownPageItems"].ToString()));
gvBatch.AllowPaging = true;
gvBatch.TopPagerRow.Visible = true;
}
}
catch (Exception ex)
{
}
}
protected void gvBatch_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "EDIT")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
string strAgentName = ((HiddenField)row.FindControl("hf_loginName")).Value.ToString();
if (strAgentName != "")
{
Response.Redirect("CustomerDetails.aspx?Name=" + strAgentName, false);
}
}
}
catch (Exception ex)
{
log.Error("gvAgentRowcommand_AgentSummary", ex);
}
}

You can keep a boolean field in your code and set its value to true whenever the select all is clicked. When loading new pages, you can check that field to automatically display all checked. The same can be done when exporting the grid also.

you can modify and use the following Method
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells["Column_Name"].Value) == false)
{
item.Cells["Column_Name"].Value = true;
}
}
}
the 'Column_name' is the name of the checkbox column. if you haven'nt named it yet you can also use the index number .
in your case its 0
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == false)
{
item.Cells[0].Value = true;
}
}
}

You should update (ArrayList)Session["BP_PrdId"] to include all the "Id"s of datasource of gridview. then bind data again.

Related

How to fix hiding datagridview object

I'm setting datagridview as object and show in windows form in Textbox change event. When open form and start texting into textbox then datagridview is show but when text is empty or null datagridview continue been visible. How can I accomplish datagridview invisible in windows form?
This is for C#. I have tried to dispose datagridview in if clause but it didn't work.
Here is my code:
public class CreateDataGridView
{
public DataGridView clientsDgv = new DataGridView();
public CreateDataGridView()
{
clientsDgv.ReadOnly = true;
clientsDgv.Name = "clientsDgv";
clientsDgv.AllowUserToAddRows = false;
clientsDgv.AllowUserToDeleteRows = false;
clientsDgv.AllowUserToResizeRows = false;
}
public DataGridView Createdgv()
{
return clientsDgv;
}
Here is my code in windows form.
//Get datagridview in windows form textbox change event
private void TxtID_TextChanged(object sender, EventArgs e)
{
switch (this.cmbSelectAction.SelectedIndex)
{
case 1:
CreateDataGridView clientsdgv = new CreateDataGridView();
//clientsdgv.clientsDgv
Controls.Add(clientsdgv.clientsDgv);
clientsdgv.clientsDgv.BringToFront();
DesignDataGridView designdgv = new DesignDataGridView();
designdgv.ClientsDataGridFormatting(clientsdgv.clientsDgv);
designdgv.ClientsDataGridPosition(clientsdgv.clientsDgv, txtID);
//SetDoubleBuffered.SetDoubleBuffering(clientsdgv.clientsDgv, true);
if (string.IsNullOrEmpty(txtID.Text) || txtID.Text == "0")
{
clientsdgv.clientsDgv.DataSource = null;
clientsdgv.clientsDgv.Update();
clientsdgv.clientsDgv.Dispose();
clientsdgv.clientsDgv.Visible = false;
return;
}
else
{
GetSqlData getSqlData = new GetSqlData();
try
{
clientsdgv.clientsDgv.SuspendLayout();
columnName = "PersonalIDBulstat";
ID = txtID.Text;
clientsdgv.clientsDgv.Visible = true;
clientsdgv.clientsDgv.DataSource = getSqlData.SearchClientsInSql(columnName, ID);
clientsdgv.clientsDgv.Update();
clientsdgv.clientsDgv.ResumeLayout();
}
catch
{
title = "Clients";
SetMessageBoxTypes.MessageBoxContactAdminOk(title);
}
}
break;
}
}
Thank you in advance!
It is my working code when form is load where dgvClients is declare as DataGridView:
private void Clients_Load(object sender, EventArgs e)
{
CreateDataGridView clientsdgv = new CreateDataGridView();
dgvClients = clientsdgv.dgvClients;
}
private void TxtID_TextChanged(object sender, EventArgs e)
{
switch (this.cmbSelectAction.SelectedIndex)
{
case 1:
Controls.Add(dgvClients);
dgvClients.BringToFront();
DesignDataGridView designdgv = new DesignDataGridView();
designdgv.ClientsDataGridPosition(dgvClients, this.txtID);
GetSqlData getSqlData = new GetSqlData();
if (string.IsNullOrEmpty(txtID.Text) || txtID.Text == "0")
{
dgvClients.DataSource = null;
dgvClients.Update();
dgvClients.Visible = false;
return;
}
else
{
try
{
dgvClients.SuspendLayout();
columnName = "PersonalIDBulstat";
ID = txtID.Text;
dgvClients.Visible = true;
dgvClients.DataSource = getSqlData.SearchClientsInSql(columnName, ID);
dgvClients.Update();
dgvClients.ResumeLayout();
}
catch
{
title = "Clients";
SetMessageBoxTypes.MessageBoxContactAdminOk(title);
}
}
break;
}
}

Master/Details ASP.NET C# DataGrid?

I want to display data Master/Details stype with DataGrid not GridView or anything else. At the present I must put a dropdownlist to do this manually. So how can do it automatically whenever we click one master item in the Master DataGrid then it link to Details DataGird , like this:
private void BindGridMaster()
{
grdReceivedNote.DataSource = ReceivedNoteService.ReceivedNote_GetByAll();
grdReceivedNote.DataBind();
if (grdReceivedNote.PageCount <= 1)
{
grdReceivedNote.PagerStyle.Visible = false;
}
else
{
grdReceivedNote.PagerStyle.Visible = true;
}
}
private void BindGridDetails()
{
grdReceivedNoteDetails.DataSource = RevNoteDetailsService.RevNoteDetails_GetByAll();
grdReceivedNoteDetails.DataBind();
if (grdReceivedNoteDetails.PageCount <= 1)
{
grdReceivedNoteDetails.PagerStyle.Visible = false;
}
else
{
grdReceivedNoteDetails.PagerStyle.Visible = true;
}
}
protected void grdReceivedNote_ItemDataBound(object sender, DataGridItemEventArgs e)
{
ListItemType itemType = e.Item.ItemType;
if ((itemType != ListItemType.Footer) && (itemType != ListItemType.Separator))
{
if (itemType == ListItemType.Header)
{
object checkBox = e.Item.FindControl("chkSelectAll");
if ((checkBox != null))
{
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelectAll_OnClick(this)");
}
}
else
{
string tableRowId = grdReceivedNote.ClientID + "_row" + e.Item.ItemIndex.ToString();
e.Item.Attributes.Add("id", tableRowId);
object checkBox = e.Item.FindControl("chkSelect");
if ((checkBox != null))
{
e.Item.Attributes.Add("onMouseMove", "Javascript:chkSelect_OnMouseMove(this)");
e.Item.Attributes.Add("onMouseOut", "Javascript:chkSelect_OnMouseOut(this," + e.Item.ItemIndex.ToString() + ")");
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelect_OnClick(this," + e.Item.ItemIndex.ToString() + ")");
}
}
}
}
protected void grdReceivedNoteDetails_ItemDataBound(object sender, DataGridItemEventArgs e)
{
ListItemType itemType = e.Item.ItemType;
if ((itemType != ListItemType.Footer) && (itemType != ListItemType.Separator))
{
if (itemType == ListItemType.Header)
{
object checkBox = e.Item.FindControl("chkSelectAll");
if ((checkBox != null))
{
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelectAll_OnClick(this)");
}
}
else
{
string tableRowId = grdReceivedNote.ClientID + "_row" + e.Item.ItemIndex.ToString();
e.Item.Attributes.Add("id", tableRowId);
object checkBox = e.Item.FindControl("chkSelect");
if ((checkBox != null))
{
e.Item.Attributes.Add("onMouseMove", "Javascript:chkSelect_OnMouseMove(this)");
e.Item.Attributes.Add("onMouseOut", "Javascript:chkSelect_OnMouseOut(this," + e.Item.ItemIndex.ToString() + ")");
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelect_OnClick(this," + e.Item.ItemIndex.ToString() + ")");
}
}
}
}
protected void grdReceivedNote_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
grdReceivedNote.CurrentPageIndex = e.NewPageIndex;
BindGridMaster();
}
protected void grdReceivedNoteDetails_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
grdReceivedNoteDetails.CurrentPageIndex = e.NewPageIndex;
BindGridMaster();
}
protected void grdReceivedNote_ItemCommand(object source, DataGridCommandEventArgs e)
{
string strCA = e.CommandArgument.ToString();
switch (e.CommandName)
{
case "Edit":
Insert = false;
Id = strCA;
ViewCustomers();
ViewRevType();
//ViewRevNote();
//ViewItems();
List<Data.ReceivedNote> listE = ReceivedNoteService.ReceivedNote_GetById(Id);
txtRevNote_No.Text = listE[0].RevNote_No;
txtRevDate.Text = listE[0].RevDate;
txtNotes.Text = listE[0].Notes;
drlCustIdAdd.SelectedValue = listE[0].CustID;
drlRevTypeIdAdd.SelectedValue = listE[0].RevTypeID;
pnViewMaster.Visible = false;
pnUpdateMaster.Visible = true;
break;
case "Delete":
ReceivedNoteService.ReceivedNote_Delete(strCA);
BindGridMaster();
break;
}
}
protected void grdReceivedNoteDetails_ItemCommand(object source, DataGridCommandEventArgs e)
{
string strCA = e.CommandArgument.ToString();
switch (e.CommandName)
{
case "Edit":
Insert = false;
Id = strCA;
//ViewCustomers();
//ViewRevType();
ViewRevNote();
ViewItems();
List<Data.RevNoteDetails> listE = RevNoteDetailsService.RevNoteDetails_GetById(Id);
txtQuantity.Text = listE[0].Quantity;
drlRevNoteIdAdd.SelectedValue = listE[0].RevNoteID;
drlItemIdAdd.SelectedValue = listE[0].ItemID;
pnlViewDetails.Visible = false;
pnlUpdateDetails.Visible = true;
break;
case "Delete":
RevNoteDetailsService.RevNoteDetails_Delete(strCA);
BindGridDetails();
break;
}
}

Datagridview c# with SQL for Professional Developer

First of all I will give short description about my App:
C# application uses sql server to share "Tasks" between team
All user see the tasks
The event happens when user check the checkbox
I use a timer to refresh the grid every 4 seconds
Timer code:
private static int second = 0;
private void timer1_Tick(object sender, EventArgs e)
{
try
{
second++;
List<Tasks> list=taskController.taskController.GetList();
_FillGridFromList(list);
_RefreshGrid();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/*reFill the grid*/
private void _RefreshGrid()
{
try
{
List<Tasks> list = taskController.taskController.GetList();
_FillGridFromList(list);
}
catch (Exception ex)
{
MessageBox.Show(this, "Unable to Retrive Data from Server", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/*This function will fill userGridView from Arraylist that get from SQL */
private void _FillGridFromList(List<Tasks> list)
{
dataGridView1.ClearSelection();
try
{
DataTable table1 = new DataTable("sheet");
System.Data.DataSet tmpSet = new System.Data.DataSet();
DataRow row = table1.NewRow();
table1.Columns.Add("ID");
table1.Columns.Add("Title");
table1.Columns.Add("Description");
table1.Columns.Add("Preiority");
table1.Columns.Add("Status");
table1.Columns.Add("Done By");
table1.Columns.Add("Start Date");
int j = 0;
for (int i = 0; i < list.Count; i++)
{
Tasks tmp = (Tasks)list[i];
row[j++] = tmp.ID;
row[j++] = tmp.Name;
row[j++] = tmp.Description;
row[j++] = tmp.Preiority;
row[j++] = tmp.Status;
row[j++] = tmp.Done_By;
row[j++] = tmp.Start_Date;
j = 0;
table1.Rows.Add(row);
row = table1.NewRow();
}
tmpSet.Tables.Add(table1);
dataGridView1.DataSource = tmpSet.Tables[0];
// dataGridView1.ReadOnly = true;
dataGridView1.Columns[1].ReadOnly = true;
dataGridView1.Columns[2].ReadOnly = true;
dataGridView1.Columns[3].ReadOnly = true;
dataGridView1.Columns[4].ReadOnly = true;
dataGridView1.Columns[5].ReadOnly = true;
dataGridView1.Columns[6].ReadOnly = true;
dataGridView1.Columns[7].ReadOnly = true;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Done_By.Trim().Length > 0)
{
dataGridView1.Rows[i].Cells[0].Value = true;
if (list[i].Done_By != utility.Util.User.Display_Name)
{
dataGridView1.Rows[i].Cells[0].ReadOnly = true;
}
else
{
dataGridView1.Rows[i].Cells[0].ReadOnly = false;
}
}
else
{
dataGridView1.Rows[i].Cells[0].Value = false;
}
}
}
catch (Exception e)
{
MessageBox.Show(this, e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView1_CellValueChanged_1(object sender, DataGridViewCellEventArgs e)
{
try
{
if(second > 5)
{
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
DataGridViewCheckBoxCell drx = (DataGridViewCheckBoxCell)dr.Cells[0];
if(sender == drx)
if (drx.Selected != null) //Cells[0] Because in cell 0th cell we have added checkbox
{
if (drx.Selected==true && dr.Cells[6].Value.ToString() == utility.Util.User.Display_Name)
{
Tasks tsk = taskController.taskController.Read(dr.Cells[1].Value + "");
{
tsk.Done_By = "";
tsk.Status = "";
taskController.taskController.Update(tsk);
}
}
else
{
if (drx.Selected !=true)
{
Tasks tsk = taskController.taskController.Read(dr.Cells[1].Value + "");
tsk.Done_By = utility.Util.User.Display_Name;
tsk.Status = "Closed";
taskController.taskController.Update(tsk);
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The main problem is that when I fill the form again the listener is called because I rebuild the gridview.
http://i.stack.imgur.com/l0Rdv.png
I solve the problem by using the below code :
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//MessageBox.Show(e.RowIndex+" "+e.ColumnIndex);
// Int32 selectedRowCount = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);
// Int32 selectedColumnCount = dataGridView1.Columns.GetColumnCount(DataGridViewElementStates.Selected);
if ( e.ColumnIndex == 0 && e.RowIndex >= 0 )
{
string x=dataGridView1.Rows[e.RowIndex-1].Cells[6].Value.ToString();
if ((bool)dataGridView1.Rows[e.RowIndex-1].Cells[0].Value == false && x!=null )
{
if(x==Util.User.Display_Name)
{
Tasks tsk = taskController.taskController.Read(dataGridView1.Rows[e.RowIndex-1].Cells[1].Value + "");
tsk.Done_By = "";
tsk.Status = "";
taskController.taskController.Update(tsk);
dataGridView1.Rows[0].Cells[1].Value = true;
}
}
else
{
if ((bool)dataGridView1.Rows[e.RowIndex-1].Cells[0].Value == true)
{
Tasks tsk = taskController.taskController.Read(dataGridView1.Rows[e.RowIndex-1].Cells[1].Value + "");
tsk.Done_By = utility.Util.User.Display_Name;
tsk.Status = "Closed";
taskController.taskController.Update(tsk);
}
}
}
}
I only change the type of listener from private void dataGridView1_CellValueChanged_1
to
private void dataGridView1_CellContentClick

Bind GridView on Button Click Event with Pagination

I'm new to asp.net and needs some help. I have a gridview with paging for every 20 records per page, I have a search button outside the gridview. What I need to do is when I click the search button, the results must be bind to gridview(which is happening now), however when the records are more than the pagesize and I need to go to the next page of the grid, the binding is lost and the binded records are the ones form the page on load event. below is my code sample.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void BindData()
{
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//SaveSelectedValues();
gvwAssociation.PageIndex = e.NewPageIndex;
//BindData();
//PopulateSelectedValues();
}
First of all you should have the following event handler for paging
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
Then, move your search/ filter logic within the search button to a private method (say "bindGridWithFilter")
TIP: Try to combine both BindData and bindGridWithFilter so when there's no filter you display all records
UPDATE
Here's some refactored code for you to get an idea what I meant above.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridWithFilter();
}
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
bindGridWithFilter();
}
private void bindGridWithFilter()
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
// If you don't have a filter you show all records
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
else
{
// This is same as the logic in your search button
// display only the filtered records
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
List<EventFile> fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
}
This should work.

how to get selected column value or name from datagrid in asp.net using c#

My code is like this : Now I have now idea how to get column name of selected row
protected void gv_imageslist_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string status;
string sts;
int result;
lblerror2.Text = "";
//((label)gv.Rows.FindControl("lbl1")).Text;
string str = gv_imageslist.c
if (str == "Status")
{
status = ((Label)gv_imageslist.Rows[e.RowIndex].FindControl("lbl_Status")).Text;
Gm.Gallery_Id = Convert.ToInt32(gv_imageslist.DataKeys[e.RowIndex].Value.ToString());
if (status == "True")
{
Gm.Is_Active = false;
}
else
{
Gm.Is_Active = true;
}
result = Gm.Change_Image_Status();
if (result == 1)
{
Build_ImageGalleryList();
}
else
{
lblerror2.Visible = true;
lblerror2.Text = "Unable to Change Status !";
}
}
else
//------For Checking of cover pic
{
sts = ((Label)gv_imageslist.Rows[e.RowIndex].FindControl("lbl_Cover")).Text;
Gm.Gallery_Id = Convert.ToInt32(gv_imageslist.DataKeys[e.RowIndex].Value.ToString());
string sp = ((Label)gv_imageslist.Rows[e.RowIndex].FindControl("lbl_category_Id")).Text;
Gm.Category_Id = Convert.ToInt32 (sp);
if (sts == "False")
{
Gm.Is_Cover = true;
}
else
{
Gm.Is_Cover = false;
}
result = Gm.Change_Gallery_Cover();
if (result == 1)
{
Build_ImageGalleryList();
}
else
{
lblerror2.Visible = true;
lblerror2.Text = "Unable To Change Cover Pic !!";
}
}
}
Try this code snippet;
gv.HeaderRow.Cells[i].Text
Why not create an object of the selected row and work with it from there?
i.e.
var selectedRow = (TYPE)gridViewName.GetFocusedRow();
You could then use the selectedRow object and call any properties belonging to it
i.e. var name = selectedRow.Name
It can be possible through DataKeyNames and Normal method also
1) 'e' as Commandargument
int index = Convert.ToInt32(e.CommandArgument);
string request = gvRequests.Rows[index].Cells[4].Text.ToString();
2) GridViewRow selectedRow = gvRequests.Rows[index];
string Id = gvRequests.DataKeys[index].Value.ToString().Trim();
string headerText=gvProductList.HeaderRow.Cells[1].Text;
protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
LinkButton lnk = (LinkButton) e.Row.FindControl("lnk");
Label lblName= (Label) e.Row.FindControl("lblName");
lnk.Attributes.Add("onclick", "getValue(" + lblName.ClientID + ");"
}
}... You can try this... method in your own way
Enjoy... ..

Categories