DevExpress: ASPxGridView GroupBy() won't work - c#

My goal is to group the data at runtime inside a grdView which added to a panel also at runtime
grdView.DataSource = tbl;
grdView.DataBind();
grdView.Settings.ShowGroupPanel = true;
grdView.BeginUpdate();
grdView.GroupBy((DevExpress.Web.ASPxGridView.GridViewDataColumn) grdView.Columns["ClmnName"]);//or an index (0) for example
grdView.EndUpdate();
any suggestions?
EDIT:
Current Code
//GRID
pnlGrids.Controls.Add(grdView);
grdView.DataSource = tbl;//Datasource
foreach (GridViewDataTextColumn clmn in grdView.Columns)//HTML
clmn.PropertiesTextEdit.EncodeHtml = false;
if (key.GroupingDataMembers.Any())//Group panel
grdView.Settings.ShowGroupPanel = true;
grdView.Images.ImageFolder = "~/App_Themes/Aqua/GridView/";//Style
grdView.Styles.CssFilePath = "~/App_Themes/Aqua/GridView/styles.css";
grdView.Styles.CssPostfix = "Aqua";
grdView.DataBind();//Bind
if (key.GroupingDataMembers.Any())//Grouping
(grdView.Columns[key.GroupingDataMembers.First().DataMember.DisplayName] as DevExpress.Web.ASPxGridView.GridViewDataColumn).GroupBy();
grdView.ExpandAll();//Expand all

The following code works fine here:
protected void Page_Load(object sender, EventArgs e) {
ASPxGridView grid = new ASPxGridView();
grid.ID = "grid";
pnl.Controls.Add(grid);
DataTable t = new DataTable();
t.Columns.Add("Id");
t.Columns.Add("Data");
for(int i = 0; i < 100; i++) {
t.Rows.Add(new object[] { i, "row " + i.ToString() });
}
grid.DataSource = t;
grid.Settings.ShowGroupPanel = true;
grid.DataBind();
(grid.Columns["Data"] as GridViewDataColumn).GroupBy();
}

Related

how can edit row when datagridview is databound

i have datagridview is bindingsurce table of database
datagridview load data from database
i wanna after get data from database edit row in datagredview using textboxs
i am using this code for Edit data
private void btn_Edit_Click(object sender, EventArgs e)
{
DataGridViewRow dr = dgvadministration.Rows[index_Row];
dr.Cells[2].Value = Convert.ToInt32(txt_Masseurs_Code.Text);
dr.Cells[4].Value = Convert.ToInt32(txt_Session_Type_Code.Text);
dr.Cells[6].Value = Convert.ToInt32(txt_C_Order_Masseurs.Text);
dr.Cells[7].Value = Convert.ToInt32(txt_Room_No.Text);
dr.Cells[8].Value = dtp_Session_Date.Text;
dr.Cells[9].Value = cbx_Session_done.Checked == true ? true : false;
dr.Cells[10].Value = txt_Session_Note.Text;
}
and get index_Row from dgvadministration_CellClick
private int index_Row;
private void dgvadministration_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
Clear_Session_Data();
index_Row = e.RowIndex;
session_Code_Serial = Convert.ToInt32(dgvadministration.SelectedRows[0].Cells[1].Value.ToString());
txt_Masseurs_Code.Text = dgvadministration.SelectedRows[0].Cells[2].Value?.ToString();
txt_Masseurs_Name.Text = dgvadministration.SelectedRows[0].Cells[3].Value?.ToString();
txt_Session_Type_Code.Text = dgvadministration.SelectedRows[0].Cells[4].Value?.ToString();
txt_Session_Type_Name.Text = dgvadministration.SelectedRows[0].Cells[5].Value?.ToString();
txt_C_Order_Masseurs.Text = dgvadministration.SelectedRows[0].Cells[6].Value?.ToString();
txt_Room_No.Text = dgvadministration.SelectedRows[0].Cells[7].Value?.ToString();
if (dgvadministration.SelectedRows[0].Cells[8].Value != null)
{
DateTime CoStartDate = (DateTime)dgvadministration.SelectedRows[0].Cells[8].Value;
dtp_Session_Date.Text = CoStartDate.ToShortDateString();
}
DataGridViewCheckBoxCell chk_Session_Done = dgvadministration.SelectedRows[0].Cells[9] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(chk_Session_Done.Value) == true)
{
cbx_Session_done.Checked = true;
}
else
{
cbx_Session_done.Checked = false;
}
txt_Session_Note.Text = dgvadministration.SelectedRows[0].Cells[10].Value?.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
but dr.Cells[2].Value is null and al dr.Cells[X].Value
despite of Convert.ToInt32(txt_Masseurs_Code.Text); is not null and other textbox
Note before load data from database this code edit row is working when add Rows programmability using this code
DataTable dt = new DataTable();
dt.Columns.Add("Session_Code");
DataRow dr = null;
for (int i = 0; i < 5; i++)
{
dr = dt.NewRow();
dr["Session_Code"] = i.ToString();
dt.Rows.Add(dr);
}
dgvadministration.DataSource = dt;
Why is this happening, and how do I Edit this Row ????

DataGridView doesn't display the data

I have an Access table which I want to display on a DataGridView, but the GridView doesn't display the data.
All the other functions inside this one works properly.
This is the function:
private void ShowSuppliersFrm_Load(object sender, EventArgs e)
{
dgvShowSupps.RowCount = dataB.GetSuppliersNumber();
dgvShowSupps.ColumnCount = 3;
dgvShowSupps.Columns[0].HeaderText = "SuppNumber";
dgvShowSupps.Columns[1].HeaderText = "SuppName";
dgvShowSupps.Columns[2].HeaderText = "SuppPhone";
Supplier[] supplierList = dataB.GetSupplierData();
int size = supplierList.Length;
for (int i = 0; i < size; i++)
{
dgvShowSupps[0, i].Value = supplierList[i].SuppNumber;
dgvShowSupps[1, i].Value = supplierList[i].SuppName;
dgvShowSupps[2, i].Value = supplierList[i].SuppPhone;
}
}
This is my table:
Normally with a datagridview, you would simply do this:
private void ShowSuppliersFrm_Load(object sender, EventArgs e)
{
var binding = new BindingSource();
binding.DataSource = dataB.GetSupplierData();
dgvShowSupps.DataSource = binding;
}
It can be a DataTable or a list of objects. Though you may have to do some data marshalling or setup on the DataGridView if it shows data that you don't want.
https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource(v=vs.110).aspx

dynamically place controls in datagrid according to condition

I am new to windows application.I have a table in which there are two fields namely,Title and Type.
In Type field i have two values "O" & "T".
Now i have to populate a datagrid with this table Title as first column and in second column depending on the Type field value i have to place a control i.e when Type field will have "O" at that time i have to place a combobox in that column and when it is "T" i have to place a text Box
i have tried a lot and googled a lot but both controls in same column is quite difficult for me as a beginner.
Plz help me with this requirement.
this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ERP_Ship.App_Code.Fleet_Person;
using ERP_Ship.App_Code.Appraisal;
using ERP_Ship.Forms.Master;
using ERP_Ship.App_Code.Common;
using ERP_Ship.App_Code.Vessel_Hardening_Measures;
namespace ERP_Ship.Forms.Reports
{
public partial class Vessel_Hardening_Measures : Form
{
// ? //
private DataSet ds = new DataSet("myDs");
private DataTable dt = new DataTable("Apprdtl");
//Define controls must be add to data grid.
private Label lblControl = new Label();
private TextBox txtControl = new TextBox();
private ComboBox cboControl = new ComboBox();
//Capture the clicked cell
private DataGrid.HitTestInfo hitTestGrid;
//Control definishion to add to DataGrid
DataGridTableStyle dataGridStyle = new DataGridTableStyle();
DataGridTextBoxColumn dataGridLableTitle = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle1 = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle2 = new DataGridTextBoxColumn();
//DataGridTextBoxColumn dataGridLable = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridTextBox = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridComboBox = new DataGridTextBoxColumn();
private System.Windows.Forms.DataGrid gv_Appraisal;
#region Form Level Variables
string _strName;
string _strCDCNo;
//DataTable dt = new DataTable();
// OracleConnection con1 = new OracleConnection(ConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString.ToString());
I_Common objCommon = new I_Common();
DataTable dt1 = new DataTable("dt1");
#endregion
#region Public Properties
public string SearchName
{
set
{
_strName = value;
}
get
{
return _strName;
}
}
public string SearchCDCNo
{
set
{
_strCDCNo = value;
}
get
{
return _strCDCNo;
}
}
#endregion
public Vessel_Hardening_Measures()
{
InitializeComponent();
InitializeControls();
Load_Year();
//for (int index = 0; index <= gv_Appraisal.Columns.Count - 1; index++)
//{
// gv_Appraisal.Columns[index].DataPropertyName = gv_Appraisal.Columns[index].Name;
//}
//gv_Appraisal.AutoGenerateColumns = false;
}
private void InitializeControls()
{
//label property
lblControl.Cursor = Cursors.Hand;
lblControl.ForeColor = Color.Red;
lblControl.Font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic);
//textbox property
txtControl.Cursor = Cursors.Hand;
txtControl.BackColor = Color.WhiteSmoke;
txtControl.ForeColor = Color.DarkSlateBlue;
txtControl.Font = new Font("Arial", 8, FontStyle.Bold);
//textbox events.
txtControl.TextChanged += new EventHandler(txtTextChanged);
string[] dropdownitems = { "Yes", "No", "Not Applicable" };
//Define and add ComboBox rows, will be added to data grid.
for (int i = 0; i < dropdownitems.Count(); i++)
cboControl.Items.Add(dropdownitems[i]);
//combobox property
cboControl.Cursor = Cursors.Hand;
cboControl.DropDownStyle = ComboBoxStyle.DropDownList;
//combobox events.
cboControl.SelectedIndexChanged += new EventHandler(cboSelectedIndexChanged);
}
private void DesignTableStyle()
{
dataGridStyle.PreferredRowHeight = 24;
dataGridStyle.MappingName = "Apprdtl";
gv_Appraisal.TableStyles.Add(dataGridStyle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle1);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle2);
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
//dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridLableTitle.HeaderText = "vhm_id";
dataGridLableTitle.MappingName = "vhm_id";
dataGridLableTitle.Width = 1;
//dataGridLableTitle.Width = 40;
dataGridLableTitle1.HeaderText = "Title";
dataGridLableTitle1.MappingName = "Title";
dataGridLableTitle1.Width = 150;
dataGridLableTitle2.HeaderText = "Type";
dataGridLableTitle2.MappingName = "Type";
dataGridLableTitle2.Width = 1;
//dataGridLableTitle2.Width = 40;
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//dataGridComboBox.HeaderText = "COMBOBOX_COL";
//dataGridComboBox.MappingName = "ComboBox_col";
//dataGridComboBox.Width = 130;
}
private void Load_DNF() // DATA NOT FOUND OF CDC NO
{
try
{
using (BL_Vessel_Hardening_Measures obj_vsl_hardening_measures = new BL_Vessel_Hardening_Measures())
{
DataTable dataTable = new DataTable();
ds = obj_vsl_hardening_measures.Get_Vessel_Hardening_Measures();
dt1 = ds.Tables[0];
DataColumn dc = new DataColumn("vhm_id");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Title");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Type");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
//Create a new column for datatable.
dc = new DataColumn("TextBox_Col", System.Type.GetType("System.String"));
//Add created column to datatable object.
dt.Columns.Add(dc);
DataRow dr;
for (int i = 0; i < dt1.Rows.Count; i++)
{
dr = dt.NewRow();
dr["vhm_id"] = dt1.Rows[i]["vhm_id"];
dr["Title"] = dt1.Rows[i]["Title"];
dr["Type"] = dt1.Rows[i]["Type"];
dr["TextBox_Col"] = "";
//dr["ComboBox_Col"] = "";
dt.Rows.Add(dr);
}
// gv_Appraisal.DataSource = ds.Tables[0];
gv_Appraisal.DataSource = dt;
ds.Tables.Remove("Apprdtl");
ds.Tables.Add(dt);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
cls_Utility.Close_Pending_Form();
Home objHome = new Home();
I_Common.CloseForm(this.MdiParent, this, objHome);
}
private void Reset_Controls()
{
//txt_CDC_NO.Text = "";
//cmb_Name.SelectedIndex = -1;
}
~Vessel_Hardening_Measures()
{
this.Close();
}
private void Vessel_Hardening_Measures_FormClosed(object sender, FormClosedEventArgs e)
{
cls_Utility.Close_Pending_Form();
}
private void Load_Year()
{
try
{
//ddl_Year.DisplayMember = "Year";
//ddl_Year.ValueMember = "Year";
objCommon.Load_Years(ddl_Year, 1);
//string str_year = "";
//str_year = DateTime.Now.AddYears(-1).Year.ToString();
//ddl_Year.Items.Add(str_year);
//str_year = DateTime.Now.Year.ToString();
//ddl_Year.Items.Add(str_year);
// ddl_Year.SelectedIndex = 1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Vessel_Hardening_Measures_Load(object sender, EventArgs e)
{
DesignTableStyle();
Load_DNF();
ERP_Ship.App_Code.Common.I_Common.MdiFormTopPanel("Vessel Hardening Measures", "Vessel Hardening Measures", this.MdiParent, true);
//ERP_Ship.App_Code.Common.I_Common.StatusInfoLabel("Double Click the Search Record to View or Edit", "I", this.MdiParent, true);
}
private void gv_Appraisal_MouseUp(object sender, MouseEventArgs e)
{
hitTestGrid = gv_Appraisal.HitTest(e.X, e.Y);
if (hitTestGrid != null)
{
//Which column of datagrid has been clicked.
//switch (hitTestGrid.Column)
//{
if (hitTestGrid.Column == 3)
{
if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "T")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//Add texbox control to datagrid.
dataGridTextBox.TextBox.Controls.Add(txtControl);
// txtControl.Text = gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString();
txtControl.Focus();
}
else if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "O")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridComboBox.HeaderText = "COMBOBOX_COL";
dataGridComboBox.MappingName = "ComboBox_col";
dataGridComboBox.Width = 130;
//Add combobox control to datagrid.
dataGridComboBox.TextBox.Controls.Add(cboControl);
cboControl.Focus();
//for (int i = 0; i < cboControl.Items.Count; i++)
//{
// if (cboControl.Items[i].ToString() == gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString())
// cboControl.SelectedIndex = i;
//}
}
}
}
}
private void txtTextChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = txtControl.Text;
}
//Combobox selected index changed event.
private void cboSelectedIndexChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = cboControl.Text;
}
}
}
There might be multiple approaches to implement functionality, you are looking for.
I found one sample on this link
Check if approach described there suits to your current requirement needs.

How to change the color of a cell of Datagridview by comparing the cell date with today's Date in C#.net?

I am new to C#,this is my first project on C# language and my backend is Mysql, I am stuck at a particular point ,I am having a form which is containing a datagridview which is binded with database value,in that i have a column "TNS_Date" It is The Expiration Date of Product ,I want that if the TNS_Date is Greater then the Current Date so the Background Colour of that particular Cell Should Get Red in colured ,How could i do this ,please help me with this
I am using winforms and till now i had tried this
foreach (DataGridViewRow row in TNSFormdgv.Rows)
{
var now = DateTime.Now;
var expirationDate = DateTime.Parse(row.Cells[15].Value.ToString());
var OneMonthBefore = expirationDate.AddDays(-30);
if (now > OneMonthBefore && now < expirationDate)
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}
else if (now > expirationDate)
{
row.DefaultCellStyle.BackColor = Color.Red;
}
}
when i am executing the Project i am getting this Error
Object reference not set to an instance of an object
This is my whole code for that particular form please check it where i am getting wrong
public partial class TNS_Subscription : Form
{
public TNS_Subscription()
{
InitializeComponent();
TNSSubscriptionForm();
}
private void TNSFormBackbtn_Click(object sender, EventArgs e)
{
new Form2().Show();
this.Hide();
}
public void TNSSubscriptionForm()
{
string ConString = "datasource=localhost;port=3306;username=root;password=ajay";
MySqlConnection conDataBase = new MySqlConnection(ConString);
MySqlCommand cmdDatabase = new MySqlCommand("Select acmecmpdetails.Cmp_Number,acmecmpdetails.Cmp_Name,acmecmpdetails.Cmp_AdminId,acmecmpdetails.Cmp_Address1,acmecmpdetails.Cmp_Country1,acmecmpdetails.Cmp_State1,acmecmpdetails.Cmp_City1,acmecmpdetails.Cmp_PostalCode,acmecmpdetails.Contact_Person1,acmecmpdetails.LandLine_Number1,acmecmpdetails.MobileNumber,acmecmpdetails.Cntct_Emailid,acmetally_detail.TallySerial_No,acmetally_detail.Tally_Release,acmetally_detail.Tally_Edition,acmetally_detail.TNS_Date,acmetally_detail.Tally_PrefPartner,acmetally_detail.Tally_accountId from acmesolutionsdatabase.acmecmpdetails INNER JOIN acmesolutionsdatabase.acmetally_detail ON acmesolutionsdatabase.acmecmpdetails.TallySerial_No= acmesolutionsdatabase.acmetally_detail.TallySerial_No;", conDataBase);
try
{
MySqlDataAdapter cddsda = new MySqlDataAdapter();
cddsda.SelectCommand = cmdDatabase;
DataTable dbdataset = new DataTable();
cddsda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
TNSFormdgv.DataSource = bsource;
cddsda.Update(dbdataset);
for(int i=0;i<TNSFormdgv.Rows.Count;i++)
{
if (Convert.ToDateTime(TNSFormdgv.Rows[i].Cells["TNS_Date"].Value.ToString()) > System.DateTime.Now.Date)
{
TNSFormdgv.Rows[i].Cells["TNS_Date"].Style.BackColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Thanks In Advance
You could simply do this:
for(int i=0;i<MyGridView.Rows.Count;i++)
{
if (Convert.ToDateTime(MyGridView.Rows[i].Cells["TNS_Date"].Value.ToString()) > System.DateTime.Now.Date)
{
MyGridView.Rows[i].Cells["TNS_Date"].Style.BackColor = System.Drawing.Color.Red;
}
}
It will change the backcolor of the cell "TNS_Date" if its value is greater than current date.
OR
You can use the index of the column TNS_Date like:
If the index of the column TNS_Date is 3, then:
for(int i=0;i<MyGridView.Rows.Count;i++)
{
if (Convert.ToDateTime(MyGridView.Rows[i].Cells[3].Value.ToString()) > System.DateTime.Now.Date)
{
MyGridView.Rows[i].Cells[3].Style.BackColor = System.Drawing.Color.Red;
}
}
I hope it would solve the problem.
Here's sample that could help:
private void Form2_Load(object sender, EventArgs e)
{
dataGridView1.DataSourceChanged += dataGridView1_DataSourceChanged;
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass { ID = 1, Name = "1", Date = DateTime.Now });
list.Add(new MyClass { ID = 2, Name = "2", Date = DateTime.Now });
list.Add(new MyClass { ID = 3, Name = "3", Date = DateTime.Now });
list.Add(new MyClass { ID = 4, Name = "4", Date = DateTime.Now.AddDays(1) });
dataGridView1.DataSource = list;
}
void dataGridView1_DataSourceChanged(object sender, EventArgs e)
{
// Loop through all the cells where date is in future
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[2].Value != null) && (DateTime)row.Cells[2].Value > DateTime.Now)
{
row.Cells[2].Style.BackColor = Color.Blue;
}
}
}
I am assuming that it's in Windows Forms as you are using datagridview.
For datagridview you'd be required to iterate through each cell of the grid to find the right cell and set the background colour.
I've created following code to do so.
void loadGrid()
{
DataTable dtData = new DataTable();
dtData.Columns.Add("TNS_Date");
DataRow dRow;
clmDate.DataPropertyName = "TNS_Date";
dRow= dtData.NewRow();
dRow["TNS_Date"] = "20-01-2014";
dtData.Rows.Add(dRow);
dRow = dtData.NewRow();
dRow["TNS_Date"] = "20-02-2014";
dtData.Rows.Add(dRow);
dRow = dtData.NewRow();
dRow["TNS_Date"] = "20-03-2014";
dtData.Rows.Add(dRow);
dgvGrid.DataSource = dtData;
for (int i = 0; i <= dgvGrid.RowCount - 1; ++i)
{
//Finding the right cell to change colour.
if(DateTime.Parse(dgvGrid["TNS_Date", i].Value.ToString()) >= DateTime.Now.Date)
dgvGrid[0, i].Style.BackColor = Color.Bisque;
}
}
If you are using asp.net datagridview then use a template field to do that. You can find more details about template field here : http://msdn.microsoft.com/en-us/library/aa479353.aspx

checking if gridview has a selected item

I have a grideview and 2 buttons. I need to only show the buttons when the gridview has a selected item. My code looks like this:
protected void Page_Load(object sender, EventArgs e)
{
btactivate.Visible = false;
btdeactivate.Visible = false;
//Show Activate and Deactivate Buttons only if an item in the gridview is selected
if (GridView1.SelectedIndex != -1)
{
btactivate.Visible = true;
btdeactivate.Visible = true;
}
else
{
btactivate.Visible = false;
btdeactivate.Visible = false;
}
}
But the problem I have now is that only when I select the second time a item in the gridview the buttons show up. I need to have the the buttons show when I select the first time. I have tried changing the selected index to "-0" but that shows the buttons all the time (even when I dont have something selected). Can anyone please help?
Try this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Col1");
dt.Columns.Add("Col2");
dt.Columns.Add("Col3");
for (int i = 0; i < 20; i++)
{
DataRow dr = dt.NewRow();
dr["Col1"] = string.Format("Row{0}Col1", i + 1);
dr["Col2"] = string.Format("Row{0}Col2", i + 1);
dr["Col3"] = string.Format("Row{0}Col3", i + 1);
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
SetButtonState();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
SetButtonState();
}
private void SetButtonState()
{
btactivate.Visible = GridView1.SelectedIndex > -1;
btdeactivate.Visible = GridView1.SelectedIndex > -1;
}

Categories

Resources