I'm trying to delete a row in Grid View programmatically
I have created this GridView
<asp:GridView ID="GridView1" CssClass="HeaderTables" runat="server" AllowPaging="True"
EmptyDataText="There is no data record to display"
AllowSorting="True" AutoGenerateColumns="false"
CellPadding="0" Height="0px" Width="800px"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="first_name" HeaderText="First name"/>
<asp:BoundField DataField="last_name" HeaderText="Last name"/>
<asp:BoundField DataField="mobile_phone" HeaderText="Mobile number"/>
<asp:BoundField DataField="email" HeaderText="Email"/>
<asp:BoundField DataField="city" HeaderText="City"/>
<asp:BoundField DataField="street_number" HeaderText="Street number"/>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" />
</asp:GridView>
and my code behind is:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (MessageBox.Show("Are you sure you want to delete this data?",
"Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mySqlString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand("DELETE FROM persons WHERE id = #id", conn);
MySqlParameter param = new MySqlParameter();
try
{
int rowID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
cmd.Parameters.AddWithValue("#id", rowID);
conn.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
I'm getting the error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Your grid doesn't set the DataKeyNames property, so this grid isn't tracking any datakeys. Probably thats why you are getting an index error.
You should set the DataKeyNames property. In your code you also need to check to make sure the collection contains elements.The datakeys collection itself may not be null, but it can contain zero elements.
Use DataKeyNames="ID" like
<asp:GridView ID="GridView1" CssClass="HeaderTables" runat="server" AllowPaging="True"
EmptyDataText="There is no data record to display" DataKeyNames="ID"
AllowSorting="True" AutoGenerateColumns="false"
CellPadding="0" Height="0px" Width="800px"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="first_name" HeaderText="First name"/>
<asp:BoundField DataField="last_name" HeaderText="Last name"/>
<asp:BoundField DataField="mobile_phone" HeaderText="Mobile number"/>
<asp:BoundField DataField="email" HeaderText="Email"/>
<asp:BoundField DataField="city" HeaderText="City"/>
<asp:BoundField DataField="street_number" HeaderText="Street number"/>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" />
</asp:GridView>
Then it will work for you
Your forgot to add DataKeyNames to your gridview
DataKeyNames="Valid Column Name" //Column name here instead of Valid Column name
Full Code below :
<asp:GridView ID="GridView1" DataKeyNames="Valid Column Name" CssClass="HeaderTables" runat="server" AllowPaging="True"
EmptyDataText="There is no data record to display"
AllowSorting="True" AutoGenerateColumns="false"
CellPadding="0" Height="0px" Width="800px"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="first_name" HeaderText="First name"/>
<asp:BoundField DataField="last_name" HeaderText="Last name"/>
<asp:BoundField DataField="mobile_phone" HeaderText="Mobile number"/>
<asp:BoundField DataField="email" HeaderText="Email"/>
<asp:BoundField DataField="city" HeaderText="City"/>
<asp:BoundField DataField="street_number" HeaderText="Street number"/>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" />
</asp:GridView>
Related
I´m trying to play around ItemStyle- Width and but this only works if i use Attribites.Add("Style"...) in my page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
...
}
gwActivity.Attributes.Add("style", "word-break:break-all;word-wrap:break-word");
}
However this is not a problem. My issue is that the column headers are affected in the ItemStyle-Width:... and i do NOT want that to be the case. Can i only play around with the rows and not the headers?
<%--************************ Gridview section ************************--%>
<asp:GridView ID="gwActivity" runat="server" AutoGenerateColumns="False" OnRowCommand="gwActivity_RowCommand" CssClass="gwActivity" >
<Columns>
<asp:BoundField DataField="ActivityID" HeaderText="ActivitID"></asp:BoundField>
</Columns>
<HeaderStyle BackColor="#E6E6E6" Font-Bold="false" Font-Names="Arial" ForeColor="#000000" />
<%-- <AlternatingRowStyle BackColor="#E6E6E6" /> --%>
</asp:GridView>
try this..
<asp:GridView ID="gwActivity" runat="server"
AutoGenerateColumns="False" OnRowCommand="gwActivity_RowCommand"
CssClass="gwActivity" >
<HeaderStyle BackColor="#E6E6E6" Font-Bold="false" ForeColor="#000000" Font-Names="Arial />
<Columns>
<asp:BoundField DataField="ActivityID" HeaderText="ActivitID"></asp:BoundField>
<asp:BoundField DataField="ActivityID" HeaderText="ActivitID" HeaderStyle-Font-Bold="false"
HeaderStyle-Font-Size="12px" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="25">
<HeaderStyle Font-Bold="False" Font-Size="12px" />
<ItemStyle Font-Size="12px" HorizontalAlign="Left" Width="200px" /> //set width you want..
</asp:BoundField>
</Columns>
</asp:GridView>
I'm trying to create multiple select buttons in grid view
however I seem to be having some issues
the record is not selected using the code below
<asp:GridView ID="GridView1" runat="server" CssClass="table table-bordered text-nowrap" AutoGenerateColumns="False" DataKeyNames="Qutation_ID" OnRowDeleting="GridView1_RowDeleting" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="Qutation_ID" HeaderText="Qutation ID" InsertVisible="False" ReadOnly="True" SortExpression="Qutation_ID" />
<asp:BoundField DataField="CustID" HeaderStyle-CssClass="hiddencol" HeaderText="Customer ID" InsertVisible="False" ItemStyle-CssClass="hiddencol" ReadOnly="True" SortExpression="Qutation_ID">
<HeaderStyle CssClass="hiddencol" />
<ItemStyle CssClass="hiddencol" />
</asp:BoundField>
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Subject" HeaderText="Subject" SortExpression="Subject" />
<asp:ButtonField Text="Click" CommandName="ActionCommand" ItemStyle-Width="30" />
</Columns>
<EmptyDataTemplate>
"No records found"
</EmptyDataTemplate>
</asp:GridView>
protected void ActionCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ActionCommand")
{
msg.Text = GridView1.SelectedRow.Cells[1].Text;
}
}
I have a gridview with paging function.
the code below is my aspx code for gridview.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" GridLines="None" Width="768px" CellPadding="4" ForeColor="#333333" OnRowDeleting="OnRowDeleting" AllowPaging="True" PageSize="20" OnPageIndexChanging="gridView_PageIndexChanging" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="SAP No" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="10%">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" OnClick="LinkButton1_Click"
Text='<%#Eval("SAPNO") %>' runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PARTNO" HeaderText="Part No" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="10%">
</asp:BoundField>
<asp:BoundField DataField="PARTDESC" HeaderText="Description" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="20%">
</asp:BoundField>
<asp:BoundField DataField="MINQTY" HeaderText="Min Qty" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%">
</asp:BoundField>
<asp:BoundField DataField="QOH" HeaderText="QOH" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%">
</asp:BoundField>
<asp:BoundField DataField="CATEGORY" HeaderText="Category" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="20%">
</asp:BoundField>
<asp:BoundField DataField="EQUIPMENT" HeaderText="Equipment" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="20%">
</asp:BoundField>
<asp:CommandField ShowDeleteButton="true" ButtonType="Image" DeleteImageUrl="Image/delete.JPG" ControlStyle-Height="20px" ControlStyle-Width="50px" HeaderText="Delete">
<HeaderStyle Width="10%" HorizontalAlign="Left" /></asp:CommandField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
<PagerSettings Mode="NextPreviousFirstLast" FirstPageText="<--" PreviousPageText="<" NextPageText=">" LastPageText="-->" />
<PagerStyle HorizontalAlign="Center" BackColor="White" />
</asp:GridView>
At the back end code, i tried to retrieve the first column and specific rows but it throw me empty. the code below is how i retrieve.
int index = Convert.ToInt32(e.RowIndex);
string sapNo1 = GridView1.Rows[index].Cells[0].Text;
string partNo = GridView1.Rows[index].Cells[1].Text;
string partDesc = GridView1.Rows[index].Cells[3].Text;
I try to show all the value for sapNo1, it throw me blank but for partNo it will show the data in the gridview.
anyone has any idea about this?
I am really appreciate your help and comment!
As your first column is a linkbutton so retrieve that as it is then find the value.
string sapNo1 = GridView1.Rows[index].Cells[0].Text; // wrong code to retrieve data from linkbutton in a gridview
Modify this as :
LinkButton linkbtn =(LinkButton)GridView1.Rows[index].FindControl("LinkButton1");
string sapNo1 = linkbtn.Text;
or
string sapNo1 =(GridView1.Rows[index].FindControl("LinkButton1") as LinkButton).Text;
You can't get the controls properties present inside TemplateField like that, you need to find the control like this:-
LinkButton LinkButton1 = (LinkButton)GridView1.Rows[index].Cells[0]
.FindControl("LinkButton1");
After this you can simply fetch the properties of this control:-
string sapNo1 = LinkButton1.Text;
you can get the link button description by the below code
protected void Link_Button_Command(object sender, CommandEventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
string name = button.ToString();
}
catch (Exception ex)
{
lbl_message.Text = ex.Message;
}
}
i am filling database from store procedure but it doesn't work, even debugger doesn't hit. What is the problem, why it is blank ? I have tried several times with nd without debugging but it doesn't work man.
protected void GridViewConductorsDevices_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
DataTable ConductorDevicesInfo = new DataTable();
int ID = Convert.ToInt32(GridViewConductorsDevices.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
ViewState["ID"] = ID;
ConductorDevicesInfo = (DataTable)ManageTransport.ManageConductorDevices.GetAssignedDevices();
this.TextBoxID.Text = GridViewConductorsDevices.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
this.DropDownListConductors.SelectedValue= ConductorDevicesInfo.Rows[0]["Conductor_ID"].ToString();
this.DropDownListDevices.SelectedValue = ConductorDevicesInfo.Rows[0]["Device_ID"].ToString();
MultiView1.ActiveViewIndex = -1;
MultiView1.ActiveViewIndex = 2;
}
catch (Exception)
{
}
finally
{
}
}
.aspx
<asp:GridView ID="GridViewConductorsDevices" runat="server" AutoGenerateColumns="False" CaptionAlign="Top"
CssClass="table table-hover table-striped table-bordered" DataKeyNames="ID" OnRowCommand="GridViewConductorsDevices_RowCommand"
Width="100%">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-CssClass="visible-desktop"
HeaderStyle-CssClass="visible-desktop">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="Conductor_ID" Visible="false" ItemStyle-CssClass="visible-desktop"
HeaderStyle-CssClass="visible-desktop">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="Device_ID" Visible="false" ItemStyle-CssClass="visible-desktop"
HeaderStyle-CssClass="visible-desktop">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="Conductor" HeaderText="Conductor"
ItemStyle-CssClass="visible-desktop"
HeaderStyle-CssClass="visible-desktop">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="Terminal" HeaderText="Terminal" ItemStyle-CssClass="visible-desktop"
HeaderStyle-CssClass="visible-desktop">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<%-- <asp:BoundField DataField="TotalDistance" HeaderText="Total Distance" ItemStyle-CssClass="visible-desktop"
HeaderStyle-CssClass="visible-desktop">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>--%>
<%-- <asp:BoundField DataField="Model" HeaderText="Model" ItemStyle-CssClass="visible-desktop"
HeaderStyle-CssClass="visible-desktop">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>--%>
<%--<asp:BoundField DataField="ChassisNo" HeaderText="Chassis No" ItemStyle-CssClass="visible-desktop"
HeaderStyle-CssClass="visible-desktop">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>--%>
<%--<asp:BoundField DataField="EngineNo" HeaderText="EngineNo" ItemStyle-CssClass="visible-desktop"
HeaderStyle-CssClass="visible-desktop">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>--%>
<asp:ButtonField Text="Edit" HeaderText="Option" ItemStyle-CssClass="visible-desktop"
HeaderStyle-CssClass="visible-desktop"></asp:ButtonField>
</Columns>
</asp:GridView>
Your Gridview, <asp:GridView ID="GridViewConductorsDevices" runat="server" > needs a datasource.
You mention a stored procedure, but it's not referenced in your posted code.
To bind data to a Gridview you need to either assign one to the GridView DataSource property in the code behind followed by a call to GridViewConductorsDevices.DataBind()
Alternatively you can provide the ID of a DataSource control to the Gridview DataSourceID property which will bind automatically during the Page Lifecycle.
However in either case, the event GridViewConductorsDevices_RowCommand will never get called as you have not defined a CommandField to trigger a row event.
I want to add a column to my gridview while page is uploading.
My gridview takes his data from SQL static tables... and I want to add a column which contains the number of the row (1,2,3...)
Part of my gridview:
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center"
AutoGenerateColumns="False" DataKeyNames="InjuryScenario_id"
DataSourceID="SqlDataSource30"
OnSelectedIndexChanged="GridView1_OnSelectedIndex" ShowHeaderWhenEmpty="True"
CellPadding="3" GridLines="None" BackColor="White" BorderColor="White"
BorderStyle="Ridge" BorderWidth="2px" CellSpacing="1">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="InjuryScenario_id" HeaderText="מספר תרחיש" ReadOnly="True" SortExpression="InjuryScenario_id" />
<asp:BoundField DataField="Cause_name" HeaderText="מנגנון" SortExpression="Cause_name" />
<asp:BoundField DataField="City_name" HeaderText="יישוב" SortExpression="City_name" />
<asp:BoundField DataField="Place_name" HeaderText="מקום" SortExpression="Place_name" />
<asp:BoundField DataField="InjuryDay" HeaderText="יום" SortExpression="InjuryDay" Visible="False"/>
<asp:BoundField DataField="InjuryMonth" HeaderText="חודש" SortExpression="InjuryMonth" Visible="False"/>
<asp:BoundField DataField="InjuryYear" HeaderText="שנה" SortExpression="InjuryYear" Visible="False"/>
<asp:TemplateField HeaderText="תאריך">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"><%#(int)Eval("InjuryDay")+"/"+ Eval("InjuryMonth")+"/"+ Eval("InjuryYear") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I've tried to use this method:
protected void Btn_AddCol_Click(object sender, EventArgs e)
{
TemplateField tf = new TemplateField();
tf.HeaderTemplate = new GridViewLabelTemplate(DataControlRowType.Header, "Col1", "Int32");
tf.ItemTemplate = new GridViewLabelTemplate(DataControlRowType.DataRow, "Col1", "Int32");
GridView1.Columns.Add(tf);
}
Thanks