Gridview Get Cells ID - c#

I want to select gridview to get the ID. My code is below. What can I do to achieve this?
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int id = Convert.ToInt32(GridView1.SelectedRow.Cells[0].ToString());
TextBox2.Text = id.ToString();
}

Check this , it may work for u ,Call cell id directly.
this.GridView1.CellClick += new System.Windows.Forms.GridViewCellEventHandler(this.GridView1_CellClick);
private void GridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
string id = GridView1.Rows[GridView1.CurrentRow.Index].Cells["ID"].Value.ToString();
textBox1.Text = id;
}
catch (Exception)
{
}
}
or change this in ur code..
string id = GridView1.Rows[GridView1.CurrentRow.Index].Cells[0].Value.ToString();
textBox1.Text = id;
Add this...
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chksec" runat="server" AutoPostBack="True" oncheckedchanged="chksec_CheckedChanged1" />
</ItemTemplate>
</asp:TemplateField>
protected void chksec_CheckedChanged1(object sender, EventArgs e)
{
Response.Write("Checkbox is checked");
}

Related

How do i get id of colunm in gridview c# asp.net and open another page using that id?

How do i get id of column in grid view c# asp.net using a button and the open another web-part that will collect information fromsl server using that id from grid-view?
I have done this for my grid view:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnView" runat="server" Text="View" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And for the information from sqlserver that is being filled in gridview the code is:
protected void GridView_Load(object sender, EventArgs e)
{
using (DBEntitiesModelConn DbContext = new DBEntitiesModelConn())
{
try
{
GridView.AutoGenerateColumns = true;
var ApplicationData = from i in DbContext.DBEntity
select new
{
CompanyName = i.Name.ToString(),
ApplicationStatus = i.Status.ToString(),
ApplicationDate = i.DateSubmitted.ToString(),
ApplicationID = i.ID.ToString(),
};
GridView.DataSource = ApplicationData.ToList();
GridView.DataBind();
}
catch (System.Data.SqlClient.SqlException ex)
{
ErrorMessage.Text = ex.Message.ToString();
}
}
}
protected void OnRowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(ViewApplicationsGrid, "Select$" + e.Row.RowIndex);
e.Row.ToolTip = "Click to select this row.";
}
}

How to hide a gridview column in a button click event out side gridview

I have a gridview as shown below and i want to hide a column named FREQ_BAND
,second column in button click named btnPmtCalculation which is out side gridview .How to do this ? i reached till this code but not able to proceed
<asp:gridview id="gvSpectrum" runat="server" headerstyle-cssclass="HomeGridHeader"
allowpaging="True" rowstyle-wrap="false" autogeneratecolumns="False" cssclass="table table-striped table-bordered"
cellpadding="4" datakeynames="FEES_CALC_FORMULA,BAND_ID,BAND,FREQ_BAND,SPECTRUM_ID" horizontalalign="Left" showfooter="true"
pagesize="10" onpageindexchanging="gvSpectrum_PageIndexChanging" onrowcommand="gvSpectrum_RowCommand">
<Columns>
<asp:BoundField DataField = "sl_num" HeaderText="SN" />
<asp:BoundField DataField = "FREQ_BAND" HeaderText="Frequency Band" />
<asp:BoundField DataField = "BW" HeaderText="Bandwidth / Quantity" />
<asp:BoundField DataField = "RANGE" HeaderText="Range" />
</Columns>
</asp:gridview>
<asp:button id="btnPmtCalculation" runat="server" text="Generate Permenant Sepctrum Invoice" onclick="btnPmtCalculation_Click">
Code I did as shown below
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
bool pemenant = true;
int spectrum_id = 0;
//Button btn = (Button)sender;
////Get the row that contains this button
//GridViewRow gvr = (GridViewRow)btn.NamingContainer;
foreach (GridViewRow row in gvSpectrum.Rows)
{
if (row.RowType == DataControlRowType.Header)
{
row.Cells[1].Visible = true;
}
}}
You can try this:
OnRowCreated
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columnIndex].Visible = false;
}
If you don't prefer the hard-coded index, the only workaround I can suggest is to provide a HeaderText for the GridViewColumn and then find the column using that HeaderText.
protected void UsersGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
((DataControlField)UsersGrid.Columns
.Cast<DataControlField>()
.Where(fld => fld.HeaderText == "Email")
.SingleOrDefault()).Visible = false;
}
OnButtonClick
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
gvSpectrum.Columns[Index].Visible = false;
}
Simple, just hide the column in the button click.
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
gvSpectrum.Columns[i].Visible = false;
}
you can change your code with this:
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
bool pemenant = true;
int spectrum_id = 0;
int columnIndex = 1;
gvSpectrum.Columns[columnIndex].Visible = false;
}
'columnIndex' The column number is for hide it
or if you want hide with column Header Text Use this code:
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
foreach(DataControlField col in gvSpectrum.Columns)
{
if (col.HeaderText == "Email")
col.Visible = false;
}
}
Try this:
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
gvSpectrum.Columns[columnindex].Visible = false;
//OR
gvSpectrum.Columns["columnname"].Visible = false;
}

Set focus in texbox at last char in an asp.net web page using c#

I have a textbox in an asp.net web page. In case of postback, I need to set focus on last char in this texbox. how can I do this using c# without using anything like jQueries..
Thanks
Here is a variation of the solution proposed in Use JavaScript to place cursor at end of text in text input element:
void btnPostBack_Click(object sender, EventArgs e)
{
txtFocus.Attributes["onfocus"] = "var value = this.value; this.value = ''; this.value = value; onfocus = null;";
txtFocus.Focus();
}
Your code like below :
asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" ontextchanged="TextBox1_TextChanged" TabIndex="1">
asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True" ontextchanged="TextBox2_TextChanged" TabIndex="2">
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void Page_PreRender(object sender, EventArgs e)
{
try
{
if (Session["event_controle"] != null)
{
TextBox controle =(TextBox) Session["event_controle"];
controle.Focus();
}
}
catch ()
{
}
}

Disable/ Hide a control inside a specific row of GridView

I have below code to create a gridview in asp.net and inside gridview I have a delete button. Below code works fine and shows Delete in all rows.
I want to hide/ Disable the Delete button in very first row. Can somebody suggest the code part?
<asp:gridview ID="Gridview1" runat="server"
ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Cat">
<ItemTemplate>
<asp:TextBox ID="TextBoxCat" runat="server" Enabled="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" >
<ItemTemplate>
<asp:LinkButton ID="DeleteItemsGridRowButton" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
You can use GridView.RowDataBound Event event.
Then find the LinkButton using FindControl method.
public class Animal
{
public int RowNumber { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Gridview1.DataSource = new List<Animal>
{
new Animal {RowNumber = 1, Name = "One"},
new Animal {RowNumber = 2, Name = "Two"},
new Animal {RowNumber = 3, Name = "Three"},
new Animal {RowNumber = 4, Name = "Four"},
};
Gridview1.DataBind();
}
}
private int _counter;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (_counter == 0)
{
var linkButton = e.Row.FindControl("DeleteItemsGridRowButton")
as LinkButton;
linkButton.Visible = false;
_counter++;
}
}
}
Try This:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(GridView1.Rows.Count>0)
{
//GridView1.Rows[0].Visible = false;
LinkButton DeleteItemsGridRowButton= (LinkButton) GridView1.Rows[0].FindControl("DeleteItemsGridRowButton");
if(DeleteItemsGridRowButton!=null)
{
DeleteItemsGridRowButton.Visible=false
}
}
}

how to assign value for drop down select item c#

i need to assign value for selected value drop down in aspx for example
dropdownlist items
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
<asp:ListItem>c</asp:ListItem>
</asp:DropDownList>
if user select any item in dropdownlist1 it should increment value 2 then
if user select any item in dropdownlist2 it should increment value 2
i need to display total
i tried this code
static int i = 0;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
i += 2;
Label1.Text = "hello"+i;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
i += 2;
Label1.Text = "hello"+i;
}
its working but problem is if user first select 1 in dropdown //i=2 then user select b //i=4 if user again select 1 //i=6. it should not increment if user select any value in particular drop down list. how to do it. any idea....
You're using a static variable so the i value will be kept between postbacks and will be common to all users, this is incorrect.
You need to store it in ViewState, HiddenField, or Session in order to keep the value between postbacks and also keep the value different for each user.
Here's what I would've done using ViewState:
private int Counter
{
get
{
if (ViewState["Counter"] == null)
{
return 0;
}
else
{
return (int)ViewState["Counter"];
}
}
set
{
ViewState["Counter"] = value;
}
}
private bool DropDown1Selected
{
get
{
if (ViewState["DropDown1Selected"] == null)
{
return false;
}
else
{
return (bool)ViewState["DropDown1Selected"];
}
}
set
{
ViewState["DropDown1Selected"] = value;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!this.DropDown1Selected)
{
this.DropDown1Selected = true;
this.Counter += 2;
}
Label1.Text = string.Format("hello{0}", this.Counter);
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
this.Counter += 2;
Label1.Text = string.Format("hello{0}", this.Counter);
}
Few of the answers above are talking about static variable getting reset after post back, this is incorrect, Static variables keep their values for the duration of the application domain. It will survive many browser sessions until you restart the web server Asp.net Static Variable Life time Across Refresh and PostBack
That being said, it is definitely not a good idea to use Static variables and instead go with the approaches suggested using Session or Viewstate.
About your question, I guess you want to increment the value only first time a value is chosen from the drop down list, to achieve this you would want to have a flag to let you know if the value is already selected, something on the below lines:
static bool DrpDown1;
static bool DrpDown2;
static int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DrpDown1 = false;
DrpDown2 = false;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DrpDown1)
{
i += 2;
Label1.Text = "hello" + i;
DrpDown1 = true;
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DrpDown2)
{
i += 2;
Label1.Text = "hello" + i;
DrpDown2 = true;
}
}
You need a temporary store like ViewState or Session to keep you values and get it back from
there.
private int GetValue()
{
return Int32.Parse(ViewState["temp"]);
}
private void SetValue(int i)
{
if(ViewState["temp"]==null)
{
ViewState["temp"]=i;
}
else
{
ViewState["temp"]= i+Int32.Parse(ViewState["temp"]);
}
}
and use it in your code as follows
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SetValue(2);
Label1.Text = string.Format("hello{0}", GetValue());
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
SetValue(2);
Label1.Text = string.Format("hello{0}", GetValue());
}

Categories

Resources