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;
}
Related
I have created a sqlite database which is loaded in DataGrid but I have two Next and Previous Buttons, it is easy to navigated between data and show it to corresponding textbox in Windows Forms with DataGridView but I am unable to find a way to do same in DataGrid .
Here is my sql database code -
string dbConnectionString = #"Data Source=emsdatabase.db;version=3;";
Loading data into DataGrid :
SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString);
try
{
sqliteCon.Open();
string Query = "select Eid,Name,Mobile,Gender,Email from employeeinfo";
SQLiteCommand createCommand = new SQLiteCommand(Query, sqliteCon);
createCommand.ExecuteNonQuery();
SQLiteDataAdapter dataAdp = new SQLiteDataAdapter(createCommand);
DataTable dt = new DataTable("employeeinfo");
dataAdp.Fill(dt);
TableDataGrid.ItemsSource = dt.DefaultView;
dataAdp.Update(dt);
sqliteCon.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I can display selected data in corresponding textboxes:
DataGrid gd = (DataGrid)sender;
DataRowView rowSelected = gd.SelectedItem as DataRowView;
if (rowSelected != null)
{
EidTextBox.Text = rowSelected["Eid"].ToString();
NameTextBox.Text = rowSelected["Name"].ToString();
MobileTextBox.Text = rowSelected["Mobile"].ToString();
GenderTextBox.Text = rowSelected["Gender"].ToString();
EmailTextBox.Text = rowSelected["Email"].ToString();
}
But Unable to show corresponding data on textbox on next or previous button click
private void PrevButton_Click(object sender, RoutedEventArgs e)
{
//?????
}
private void NextButton_Click(object sender, RoutedEventArgs e)
{
//?????
}
The trick is to change SelectedIndex or SelectedItem.
private void PreviousClick(object sender, RoutedEventArgs e)
{
if (TableDataGrid.SelectedIndex > 0)
TableDataGrid.SelectedIndex--;
}
private void NextClick(object sender, RoutedEventArgs e)
{
if (TableDataGrid.SelectedIndex < TableDataGrid.Items.Count - 1)
TableDataGrid.SelectedIndex++;
}
We can find previous and next DataRowView in DataView (except when very first or last rows are selected respectively). If navigation is possible, then change DataGrid.SelectedItem:
private void PreviousClick(object sender, RoutedEventArgs e)
{
DataRowView rowSelected = TableDataGrid.SelectedItem as DataRowView;
if (rowSelected == null)
return;
int idx = GetDataRowViewIndex(rowSelected);
if (idx > 0)
TableDataGrid.SelectedItem = rowSelected.DataView[idx - 1];
}
private void NextClick(object sender, RoutedEventArgs e)
{
DataRowView rowSelected = TableDataGrid.SelectedItem as DataRowView;
if (rowSelected == null)
return;
int idx = GetDataRowViewIndex(rowSelected);
if (idx < rowSelected.DataView.Count - 1)
TableDataGrid.SelectedItem = rowSelected.DataView[idx + 1];
}
int GetDataRowViewIndex(DataRowView row)
{
for (int i = 0; i < row.DataView.Count; i++)
if (row.DataView[i] == row)
return i;
return -1;
}
I have a screen containing infragistics windows editable grid and winforms button.
On Enter key, the new row gets added in ultrawin grid. Instead i need to fire winforms button event.
Only on tab, it should navigate to next cell and when it reaches last cell, it should navigate to next row.
You can handle UltraGrid's BeforeRowUpdate event and invoke UltraButton's perform click before the new row template is about to be commited.
public partial class Form1 : Form
{
private bool _IsEnterKeyDown = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ultraGrid1.KeyDown += new KeyEventHandler(ultraGrid1_KeyDown);
ultraGrid1.BeforeRowUpdate += new CancelableRowEventHandler(ultraGrid1_BeforeRowUpdate);
ultraGrid1.InitializeLayout += new Infragistics.Win.UltraWinGrid.InitializeLayoutEventHandler(ultraGrid1_InitializeLayout);
ultraGrid1.DataSource = GetDataTable();
}
private void ultraGrid1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
_IsEnterKeyDown = true;
}
}
private void ultraGrid1_BeforeRowUpdate(object sender, CancelableRowEventArgs e)
{
if (e.Row.IsAddRow && _IsEnterKeyDown)
{
_IsEnterKeyDown = false;
ultraButton1.PerformClick();
}
}
private void ultraButton1_Click(object sender, EventArgs e)
{
MessageBox.Show("Button click event raised!");
}
private void ultraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
{
e.Layout.Override.AllowAddNew = AllowAddNew.TemplateOnBottom;
}
private DataTable GetDataTable(int rows = 10)
{
DataTable table = new DataTable("Table1");
table.Columns.Add("Boolean column", typeof(bool));
table.Columns.Add("Integer column", typeof(int));
table.Columns.Add("DateTime column", typeof(DateTime));
table.Columns.Add("String column", typeof(string));
for (int i = 0; i < rows; i++)
{
DataRow row = table.NewRow();
row["Boolean column"] = i % 2 == 0 ? true : false;
row["Integer column"] = i;
row["String column"] = "text";
row["DateTime column"] = DateTime.Today.AddDays(i);
table.Rows.Add(row);
}
return table;
}
}
I am updating gridview after selecting row and then clicking edit which works perfectly but one thing is annoying me that whenever i visit that gridview that it shows that ROW SELECTED and Colored. Why ? i want fresh gridview with no record of previous selected data.
CODE:
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int ComplainantTypeID = Convert.ToInt32(txtSelectedID.Text.Trim());
ComplainantTypeBizz comBizz = new ComplainantTypeBizz(txtName.Text);
ManageComplainantType mngComplainantType = new ManageComplainantType();
bool Result = mngComplainantType.Update(comBizz, ComplainantTypeID);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtName);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
You have to bind the data to the gridview (GridView.DataBind();) after you edit it in the RowUpdated event and set the GridView.SelectedIndex = -1; after each data bind to unselect any row in your grid.
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
GridView1.DataBind();
GridView1.SelectedIndex = -1;
}
Hope this helps.
I have a dropdown which is bound to a database. On its index change there is a function that add some button in a panel based upon selected value.
I am reading those button in page_init event but still I get null values, i.e. event bound with the button never fires.
Here is my code and dropdownlist1 is the dropdown that is adding dynamic button.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
colorgroupsTableAdapters.master_color_groupTableAdapter ta
= new colorgroupsTableAdapters.master_color_groupTableAdapter();
DataTable dt = ta.GetData();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = dt.Columns[1].ToString();
DropDownList1.DataValueField = dt.Columns[0].ToString();
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select One", "0"));
}
}
protected void Page_Init(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
bindcolors();
}
}
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
}
protected void DropDownList2_DataBound(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex < 1)
{
DropDownList2.Items.Clear();
}
DropDownList2.Items.Insert(0, new ListItem("Select One", "0"));
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["dd"] = DropDownList1.SelectedIndex;
bindcolors();
}
void bindcolors()
{
if (DropDownList1.SelectedIndex > 0)
{
addcolorgroupsTableAdapters.groupavailablecolorTableAdapter ta
= new addcolorgroupsTableAdapters.groupavailablecolorTableAdapter();
DataTable dt = ta.GetData(int.Parse(DropDownList1.SelectedValue));
HtmlTable ht = new HtmlTable();
ht.Width = "90%";
ht.Border = 1;
for (int i = 0; i < dt.Rows.Count; i++)
{
HtmlTableRow tr = new HtmlTableRow();
HtmlTableCell tc1 = new HtmlTableCell();
HtmlTableCell tc2 = new HtmlTableCell();
HtmlTableCell tc3 = new HtmlTableCell();
object[] ob = dt.Rows[i].ItemArray;
tc1.InnerHtml = ob[0].ToString();
tc2.InnerHtml = ob[1].ToString();
tc2.BgColor = "#" + ob[1].ToString();
Button b = new Button();
b.Text = "Remove";
b.CommandArgument = ob[0].ToString();
AjaxControlToolkit.ConfirmButtonExtender cb
= new AjaxControlToolkit.ConfirmButtonExtender();
cb.ConfirmText = "Are You Sure To Delete This Color From The Group?";
b.ID = "Bo" + ob[0].ToString();
b.EnableViewState = true;
b.Click += new EventHandler(b_Click);
cb.TargetControlID = "Bo" + ob[0].ToString();
tc3.Controls.Add(b);
tc3.Controls.Add(cb);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tr.Cells.Add(tc3);
ht.Rows.Add(tr);
}
Panel1.Controls.Add(ht);
}
}
void b_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
int grp = int.Parse(DropDownList1.SelectedValue);
int clid = int.Parse(b.CommandArgument);
addcolorgroupsTableAdapters.QueriesTableAdapter ta
= new addcolorgroupsTableAdapters.QueriesTableAdapter();
ta.DeleteQuery_group_color(grp, clid);
DropDownList2.DataBind();
bindcolors();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex > 0 && DropDownList2.SelectedIndex > 0)
{
int grp = int.Parse(DropDownList1.SelectedValue);
int clid = int.Parse(DropDownList2.SelectedValue);
addcolorgroupsTableAdapters.QueriesTableAdapter ta
= new addcolorgroupsTableAdapters.QueriesTableAdapter();
ta.Insert_into_group_color(grp, clid);
DropDownList2.DataBind();
bindcolors();
}
}
Please tell what I am doing wrong?
I think the problem is the check for SelectedIndex > 0 in bindControls. The reason is that ViewState is evaluated between the Init and Load so the value for the SelectedIndex property is not set yet (and therefore = -1).
You could try a different approach: use a Repeater control that is databound to the results of the database query. This way, the general structure can be defined in the Repeater and its ItemTemplate. Also the EventHandlers are registered in the ItemTemplate.
You can reset the DataSource of the Repeater whenever the SelectedIndex of the Combobox changes and do not need to recreate the controls dynamically in init.
Your code should be much shorter and behave more deterministic.
How can i get multiple selected rows in gridview using c# code & that selected rows i have to display in another form which also have gridview
public partial class WindowForm: Form
{
private DataTable dataTable = new DataTable();
//This will contain all the selected rows.
private List<DataGridViewRow> selectedRows = new List<DataGridViewRow>();
public WindowForm()
{
InitializeComponent();
dataTable .Columns.Add("Column1");
dataTable .Columns.Add("Column2");
dataTable .Columns.Add("Column3");
for (int i = 0; i < 30; i++)
{
dataTable .Rows.Add(i, "Row" + i.ToString(), "Item" + i.ToString());
}
dataGridView1.DataSource = dataTable ;
//This will select full row of a grid
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//This will allow multi selection
dataGridView1.MultiSelect = true;
dataGridView1.CurrentCellChanged += new EventHandler(dataGridView1_CurrentCellChanged);
dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
}
void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
PerformSelection(dataGridView1, selectedRows);
}
void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
if (selectedRows.Contains(dataGridView1.CurrentRow))
{
selectedRows.Remove(dataGridView1.CurrentRow);
}
else
{
selectedRows.Add(dataGridView1.CurrentRow);
}
PerformSelection(this.dataGridView1, selectedRows);
}
private void PerformSelection(DataGridView dgv, List<DataGridViewRow> selectedRowsCollection)
{
foreach (DataGridViewRow dgvRow in dgv.Rows)
{
if (selectedRowsCollection.Contains(dgvRow))
{
dgvRow.Selected = true;
}
else
{
dgvRow.Selected = false;
}
}
}
}