How to show empty data row in gridview control - c#

Here I am working with gridview here is the gidview binding
conn = new SqlConnection(strconnection);
string squery = "sql query";
da = new SqlDataAdapter(squery, conn);
ds = new DataSet();
da.Fill(ds, "tbl1");
GridView1.DataSource = ds;
GridView1.DataBind();
This the gridview control asp code
<asp:GridView ID="GridView1" runat="server" GridLines="None"
HeaderStyle-CssClass="grid_header"
RowStyle-CssClass="grid_item"
RowStyle-Height="30px"
AutoGenerateColumns="false" Width="775px" EmptyDataText="Empty">
<Columns>
<asp:BoundField HeaderText="Order Code" DataField="ordercode"
HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left" />
<asp:BoundField HeaderText="Transation Code" DataField="transcode"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Plan Name" DataField="product"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Plan Started" DataField="Start_d"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Plan Ending" DataField="End_d"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:CheckBoxField HeaderText="Payed" DataField="Payed"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Pay Date" DataField="PayDate"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Payed Amt" DataField="amtpaid"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Pay Amt" DataField="PayAmount"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
</Columns>
</asp:GridView>
This is result emp like this
Header1 header2 header3 header4
1 asdas 22sdas asdasda
2 sasa asdasas
3 asdas
4 asdasas
like this result
Here my problem is I want show the NULL places just show the "EMPTY" Message. How can I do that?

You can use NullDisplayText="EMPTY" NullDisplayText Attribute
<asp:BoundField DataField="transcode"
NullDisplayText="EMPTY"
HeaderText="header2"/>
If what is coming from your DB is not NULL but an empty string, you will need to use template field
<asp:TemplateField HeaderText="header2">
<ItemTemplate>
<%# Eval("transcode").ToString() == "" ? "EMPTY" : Eval("transcode").ToString() %>
</ItemTemplate>
</asp:TemplateField>

Check out BoundField.NullDisplayText
Gets or sets the caption displayed for a field when the field's value
is null.
Sometimes a field's value is stored as null in the data source. You can specify a custom caption to display for fields that have a null value by setting the NullDisplayText property.
In your case, you can use it like;
<asp:BoundField NullDisplayText="EMPTY" HeaderText="Order Code" DataField="ordercode" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" />
Since you didn't write your sql query, as an alternative, you can use ISNULL functions for your columns.
Replaces NULL with the specified replacement value.
For example;
SELECT ISNULL(Column1, "EMPTY")
Since you asked, How to change null text color? You can use RowDataBound event for this process. For example;
<asp:GridView ID="gridview1" runat="server" OnRowDataBound="RowDataBound">
</asp:GridView>
protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Use for loop for based all rows.
if(e.Row.Cells[i].Text == "EMPTY")
e.Row.Cells[i].BackColor = Color.Red;
}
}

You just need to add :
NullDisplayText="Empty"
Like:
<asp:BoundField HeaderText="Order Code" DataField="ordercode" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" NullDisplayText="Empty" />

Related

Display Names instead of Id in a GridView whose value is there in different table using asp.net

I have a gridView in which i have two foreign keys whose value is there in different table i am able to display only Id but i need to display its name based on its Id how to achieve it using asp.net
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#2A3F54" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false" Width="100%" Height="100%" CellSpacing="30" CellPadding="50" OnPageIndexChanging="OnPageIndexChanging">
<Columns>
<asp:BoundField DataField="order_id" HeaderText="ORDER ID" ItemStyle-Width="30" ItemStyle-Height="35" />
<asp:BoundField DataField="order_ref_no" HeaderText="ORDER REF NO" ItemStyle-Width="150" />
<asp:BoundField DataField="order_date" HeaderText="ORDER DATE" ItemStyle-Width="150" />
<asp:BoundField DataField="customer_id" HeaderText="CUSTOMER ID" ItemStyle-Width="150" />
<asp:BoundField DataField="first_name" HeaderText="USER NAME" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
my asp.net code
string customerText= customerDetails.SelectedItem.Value;
string queries = #"select * from app_order_master inner join app_user on app_user.user_id = app_order_master.user_id where app_order_master.user_id=" + customerText;;
using (DataTable dt = SMSDBHelperFE.ExecuteReaderDataTable(CommandType.Text, queries, null))
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Now i am only able to join one id value (user name) using inner join but i need to display customer name instead of ID How to achieve it using asp.net

PageIndex changes but data stays the same

I have a GridView that I bind a list to from data retrieved via edmx. My issue is when I click on pagers, the page changes, and I have debugged and know that it's changing the value, but it always just shows the data from the first page. What am I missing? Oh, and I call LoadAllRequestsData() from Page_Load in an if(!Page.IsPostBack).
<cm:GridControl runat="server" ID="gvAllRequests" DataKeyNames="Number" OnPageIndexChanging="AllRequestsGridViewPageIndexChanging" ShowHeaderWhenEmpty="True" EmptyDataText="No requests to show." >
<Columns>
<asp:BoundField DataField="Number" HeaderText="Number" SortExpression="Number" InsertVisible="False" ReadOnly="True"></asp:BoundField>
<asp:BoundField DataField="CustomerId" HeaderText="CustomerId" SortExpression="CustomerId" Visible="False"></asp:BoundField>
<asp:BoundField DataField="Customer" HeaderText="Customer" SortExpression="Customer" Visible="False"></asp:BoundField>
<asp:BoundField DataField="TypeId" HeaderText="TypeId" SortExpression="TypeId" Visible="False"/>
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type"></asp:BoundField>
<asp:BoundField DataField="Note" HeaderText="Note" SortExpression="Note"/>
<asp:BoundField DataField="RequestedOn" HeaderText="Requested On" SortExpression="RequestedOn"/>
<asp:BoundField DataField="RequestedById" HeaderText="RequestedById" SortExpression="RequestedById" Visible="False" />
<asp:BoundField DataField="RequestedBy" HeaderText="Requested By" SortExpression="RequestedBy" />
<asp:BoundField DataField="CompletedOn" HeaderText="Completed On" SortExpression="CompletedOn" />
<asp:BoundField DataField="CompletedById" HeaderText="CompletedById" SortExpression="CompletedById" Visible="False"/>
<asp:BoundField DataField="CompletedBy" HeaderText="Completed By" SortExpression="CompletedBy" />
<asp:BoundField DataField="LastModifiedOn" HeaderText="LastModified On" SortExpression="LastModifiedOn" />
<asp:BoundField DataField="LastModifiedById" HeaderText="LastModifiedById" SortExpression="LastModifiedById" Visible="False"/>
<asp:BoundField DataField="LastModifiedBy" HeaderText="LastModified By" SortExpression="LastModifiedBy" />
<asp:CheckBoxField DataField="IsDeleted" HeaderText="IsDeleted" SortExpression="IsDeleted" Visible="False"/>
</Columns>
</cm:GridControl>
private void LoadAllRequestsData(string sortExpression = "RequestedOn", SortDirection sortDirection = SortDirection.Descending)
{
var db = new CrewManagerEntities();
var list = db.GetAllRequestsByUserId(_customerId).ToList();
if (!string.IsNullOrEmpty(sortExpression))
{
list = list.AsQueryable().OrderBy(sortExpression + " " + (sortDirection == SortDirection.Ascending ? "ASC" : "DESC")).ToList();
gvAllRequests.SetSort(sortExpression, sortDirection);
}
gvAllRequests.DataSource = list;
gvAllRequests.DataBind();
}
protected void AllRequestsGridViewPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvAllRequests.PageIndex = e.NewPageIndex;
LoadAllRequestsData();
}
Edit: So, I tried using SqlDataSource instead of doing call in codebehind and using a list and the paging works. That is fine but I would like to know why the list doesn't work as there may be instances where I need to use a list source. Any ideas?

Gridview controllers null after inserting column

I am developing a Web App for managing Student exam entries but I am coming across an issue with my gridview.
The basic idea is that a user can go on and enter and update details on a students exam. Complications arise when certain subjects require different fields to be populated and this is where my issue is.
The exception is thrown when the Save Button method is run. I get a Null Object reference thrown when running the AddAudit and UpdateRecord methods. After some debugging from the looks of it the issue is the controls (ddlDate, txtAssesmentLevel etc) are not being declared from the FindCotrol method of the gridview meaning when the AddAudit and UpdateRecord methods are called they point to a null controller.
Be aware that this issue does not occur when the code is not "C2555" which leads me to suspect the issue is with dynamically adding columns and controls getting muddled up though i am not sure.
Any assistance would be great and feel free to ask for more information.
Below is my basic code:
Page Load Method
protected void Page_Load(object sender, EventArgs e){
if(!IsPostBack){
//Selected class passed through
selectedClass sc = (selectedClass)Session["selectedClass"] as selectedClass;
//Get Class Code
lblAosCode.Text = sc.getAOSCode();
//If class is English
if(lblAosCode.Text == "C2555"){
TemplateField speakingListening = new TemplateField();
speakingListening.HeaderText = "Speaking and Listening";
dgvSelectedClasses.Columns.Insert(7, speakingListening);
}
//Populate Gridview
DataTable dsSelectedClasses = AccessData.getSelectedClasses(sc.getAOSCode(), sc.getAOSPeriod(), sc.getDescription());
dgvSelectedClasses.DataSource = dsSelectedClasses;
dgvSelectedClasses.DataBind();
//Check if txtAssesmentLevel is populated
for (int index = 0; index < dgvSelectedClasses.Rows.Count; index++)
{
TextBox txtAssessmentLevel = (TextBox)dgvSelectedClasses.Rows[index].FindControl("txtAssessmentLevel");
if (dgvBefore.Rows[index].Cells[4].Text != " ")
{
txtAssessmentLevel.ReadOnly = true;
}
}
}
}
Save Method (Exception Thrown)
protected void btnSave_Click(object sender, EventArgs e)
{
for (int i = 0; i < dgvSelectedClasses.Rows.Count; i++)
{
DropDownList ddlL1L2 = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlL1L2");
DropDownList ddlExamDate = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlExamDate");
TextBox txtAssessmentLevel = (TextBox)dgvSelectedClasses.Rows[i].FindControl("txtAssessmentLevel");
DropDownList ddlSpeakingListening = null;
if (lblAosCode.Text.Contains("C2555"))
{
ddlSpeakingListening = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlSpeakingListening");
}
if (IsPostBack)
{
if (lblAosCode.Text.Contains("C2555"))
{
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Assessment Level", txtAssessmentLevel.Text, dgvBefore.Rows[i].Cells[4].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam request L1 or L2", ddlL1L2.SelectedValue, dgvBefore.Rows[i].Cells[14].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam Date", ddlExamDate.SelectedValue, dgvBefore.Rows[i].Cells[15].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Speaking and Listening", ddlSpeakingListening.SelectedValue, dgvBefore.Rows[i].Cells[7].Text);
AccessData.updateRecord(txtAssessmentLevel.Text, ddlL1L2.SelectedValue, ddlExamDate.SelectedValue, lblAosCode.Text, lblAosPeriod.Text, dgvSelectedClasses.Rows[i].Cells[0].Text, ddlSpeakingListening.SelectedValue);
}
else
{
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Assessment Level", txtAssessmentLevel.Text, dgvBefore.Rows[i].Cells[4].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam request L1 or L2", ddlL1L2.SelectedValue, dgvBefore.Rows[i].Cells[13].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam Date", ddlExamDate.SelectedValue, dgvBefore.Rows[i].Cells[14].Text);
AccessData.updateRecord(txtAssessmentLevel.Text, ddlL1L2.SelectedValue, ddlExamDate.SelectedValue, lblAosCode.Text, lblAosPeriod.Text, dgvSelectedClasses.Rows[i].Cells[0].Text);
}
}
}
Response.Redirect("~/contact");
}
On Row Data Bound
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (lblAosCode.Text.Contains("C2555"))
{
DropDownList ddlSpeakingListening = new DropDownList();
ddlSpeakingListening.ID = "ddlSpeakingListening";
ddlSpeakingListening.Items.Add("L1");
ddlSpeakingListening.Items.Add("L2");
ddlSpeakingListening.Items.Add("Entry");
ddlSpeakingListening.Items.Add("NS");
e.Row.Cells[7].Controls.Add(ddlSpeakingListening);
}
}
}
ASP.NET
<asp:GridView ID="dgvSelectedClasses" runat="server" AutoGenerateColumns="False" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="True" />
<asp:BoundField DataField="StageCode" HeaderText="Stage Code" ReadOnly="True" />
<asp:BoundField DataField="Forename" HeaderText="Forename" ReadOnly="True" />
<asp:BoundField HeaderText="Surname" DataField="Surname" />
<asp:TemplateField HeaderText="Assessment Level">
<ItemTemplate>
<asp:TextBox ID="txtAssessmentLevel" Text ='<%#Bind("AssessmetLevel") %>' runat="server" Width="50px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TargetLevel" HeaderText="Target Level" />
<asp:BoundField DataField="Achievelevel" HeaderText="Achieve Level" />
<asp:BoundField DataField="FELSOutcome" HeaderText="FELS Outcome" />
<asp:BoundField DataField="Registration" HeaderText="Registration" />
<asp:BoundField DataField="DateSpreadsheetSent" HeaderText="Last Update" />
<asp:BoundField DataField="Dayofclass" HeaderText="Day of class" />
<asp:BoundField DataField="Timeofclass" HeaderText="Time of class" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:TemplateField HeaderText="Exam request L1 or L2" >
<ItemTemplate>
<asp:DropDownList ID="ddlL1L2" runat="server" >
<asp:ListItem>Not Set</asp:ListItem>
<asp:ListItem>L1</asp:ListItem>
<asp:ListItem>L2</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam date">
<ItemTemplate>
<asp:DropDownList ID="ddlExamDate" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="dgvBefore" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="True" />
<asp:BoundField DataField="StageCode" HeaderText="Stage Code" ReadOnly="True" />
<asp:BoundField DataField="Forename" HeaderText="Forename" ReadOnly="True" />
<asp:BoundField HeaderText="Surname" DataField="Surname" />
<asp:BoundField DataField="AssessmetLevel" HeaderText="Assessment Level" NullDisplayText=" "/>
<asp:BoundField DataField="TargetLevel" HeaderText="Target Level" />
<asp:BoundField DataField="AchieveLevel" HeaderText="Achieve Level" />
<asp:BoundField DataField="FELSOutcome" HeaderText="FELS Outcome" />
<asp:BoundField DataField="Registration" HeaderText="Registration" />
<asp:BoundField DataField="DateSpreadsheetSent" HeaderText="Date Spreadsheet Sent" />
<asp:BoundField DataField="Dayofclass" HeaderText="Day of class" />
<asp:BoundField DataField="Timeofclass" HeaderText="Time of class" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="ExamrequestL1orL2" HeaderText="Exam request L1 or L2" />
<asp:BoundField DataField="Examdate" HeaderText="Exam date" />
<asp:BoundField DataField="Reviewed" HeaderText="Reviewed" />
</Columns>
</asp:GridView>
P.S. This is my first question hopefully it makes sense and I am open to pointers :)
Edit: The page load method does include code to populate dgvBefore as well as a few authentications thing i just forgot to include it.
I think you need to add the drop down list column on every postback. Refer this link : https://www.codeproject.com/Tips/682689/Add-populated-dropdownlist-to-GridView-dynamically

Make asp buttonfield visible at runtime

I have an <asp:ButtonField> inside a gridview. How do I target the button in the gridview to make it Visible on runtime based on a condition ? I am not able to target it since it doesnt have the ID property. I am stuck here. Here is the code below
<asp:GridView ID="OrdersDataList1" runat="server" DataKeyNames="OrderID" Width="100%" SkinID="Gridview" OnPageIndexChanging="orders_PageIndexChanging"
EmptyDataText="You have no orders." AllowSorting="True" OnSorting="OnSort" AllowPaging="true" PageSize="15" AutoGenerateColumns="False" OnRowCommand="updateStatus">
<Columns>
<asp:BoundField DataField="CustomerUser_ID" HeaderText="UserID" Visible="true" />
<asp:BoundField DataField="OrderID" HeaderText="OrderNo" InsertVisible="False" ReadOnly="True" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" SortExpression="OrderID" />
<asp:BoundField DataField="OrderDate" HeaderText="OrderDate" SortExpression="OrderDate" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"/>
<asp:BoundField DataField="Base" HeaderText="Base" DataFormatString="{0:C}" SortExpression="Base" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"/>
<asp:BoundField DataField="Freight" HeaderText="Freight" DataFormatString="{0:C}" SortExpression="Freight" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"/>
<asp:BoundField DataField="Total" HeaderText="Total" DataFormatString="{0:C}" SortExpression="Total" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"/>
<asp:BoundField DataField="Products" HeaderText="Products" SortExpression="Products" DataFormatString="{0} product" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="Units" HeaderText="Units" SortExpression="Units" DataFormatString="{0} units" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="OrderStatusName" HeaderText="Current Status" SortExpression="OrderStatusName" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="OrderStatusID" HeaderText="Orderstatusid" Visible="true" />
<asp:BoundField DataField="OrderTracking_ID" HeaderText="TrackingNo" SortExpression="OrderTracking_ID" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<%# GetViewOrderLink(Eval("OrderID").ToString(), Eval("OrderState").ToString())%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Change Status" SortExpression="OrderStatusName">
<ItemTemplate>
<asp:DropDownList ID="OrderStatusDD" runat="server"
DataSourceID="OrdersStatuses" DataTextField="OrderStatusName" DataValueField="OrderStatusID" Visible="false">
</asp:DropDownList>
<asp:SqlDataSource ID="OrdersStatuses" runat="server"
ConnectionString="<%$ ConnectionStrings:SqlConn %>"
SelectCommand="SELECT [OrderStatusID], [OrderStatusName] FROM [Orders_Statuses] where OrderStatusID = 2 or OrderStatusID = 8 ORDER BY [OrderStatusName]">
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" Text="Update status" Visible="false" HeaderText="Change Status" />
</Columns>
</asp:GridView>
PS I have the onrowCommand set on the gridview to listen to button click in gridview
You need to create RowCreated event for the gridview example
Before the GridView control can be rendered, a GridViewRow object must be created for each row in the control. The RowCreated event is raised when each row in the GridView control is created. This enables you to provide an event-handling method that performs a custom routine, such as adding custom content to a row, whenever this event occurs.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
OR
<asp:GridView runat="server" ID="GV1" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Reject"
Visible='<%# IsOverAgeLimit((Decimal)Eval("Age")) %>'
CommandName="Select"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected Boolean IsOverAgeLimit(Decimal Age) {
return Age > 35M;
}
Reference example
You can use the RowCreated event in the GridView as follows:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
Button btn = (Button) e.Row.Cells[12].Controls[0];
if(1==1)
{
btn.Visible = true;
}
}
((BoundField)grv_selec.Columns[1]).DataFormatString = "{0:N2}";

Deleting in gridview not working

i designed a page for admin to search users from database table using a Get button and delete users in gridview
This my source coding..
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" DataKeyNames="username" EnableModelValidation="True" OnRowDeleting="GridView1_RowDeleting" OnSelectedIndexChanged="GridView1_SelectedIndexChanged1">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="adm" HeaderText="adm" SortExpression="adm" />
<asp:BoundField DataField="mobno" HeaderText="mobno" SortExpression="mobno" />
<asp:BoundField DataField="branch" HeaderText="branch" SortExpression="branch" />
<asp:BoundField DataField="year" HeaderText="year" SortExpression="year" />
<asp:BoundField DataField="username" HeaderText="username" ReadOnly="True" SortExpression="username" />
<asp:BoundField DataField="password" HeaderText="password" SortExpression="password" />
<asp:BoundField DataField="usertype" HeaderText="usertype" SortExpression="usertype" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CanteenConnectionString %>" SelectCommand="SELECT * FROM [Hosteller]" DeleteCommand="DELETE FROM Hosteller WHERE (username = #username)">
<DeleteParameters>
<asp:Parameter Name="username" />
</DeleteParameters>
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</form>
protected void btnget_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string ConString = "Data Source=sheikha-pc\\sqlexpress;Initial Catalog=Canteen;Integrated Security=True";
SqlConnection con = new SqlConnection(ConString);
string qry = "select id,name,adm,mobno,branch,year,username,password,usertype from Hosteller where adm='" + txtsearch1.Text + "'";
SqlDataAdapter adpt = new SqlDataAdapter(qry, con);
adpt.Fill(dt);
if (dt.Rows.Count == 0)
{
GridView1.EmptyDataText = "No data found";
GridView1.DataBind();
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
this is the coding that i wrote for GET button
the problem is when i click on delete it doesnt work! please help.........
It looks like the issue here is that you are overriding the data source in your code behind. If you comment out the code in "btnget_Click" and add the datasource to GridView1 it should work to delete.
<asp:GridView ID="GridView1" DataSourceID="SqlDataSource1" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" DataKeyNames="username" EnableModelValidation="True" OnRowDeleting="GridView1_RowDeleting" OnSelectedIndexChanged="GridView1_SelectedIndexChanged1">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="adm" HeaderText="adm" SortExpression="adm" />
<asp:BoundField DataField="mobno" HeaderText="mobno" SortExpression="mobno" />
<asp:BoundField DataField="branch" HeaderText="branch" SortExpression="branch" />
<asp:BoundField DataField="year" HeaderText="year" SortExpression="year" />
<asp:BoundField DataField="username" HeaderText="username" ReadOnly="True" SortExpression="username" />
<asp:BoundField DataField="password" HeaderText="password" SortExpression="password" />
<asp:BoundField DataField="usertype" HeaderText="usertype" SortExpression="usertype" />
</Columns>
</asp:GridView>
And the code behind:
protected void btnget_Click(object sender, EventArgs e)
{
}
This might not be what you want though. This will load the data on page load so the user will not need to click the button in order to get the results.
If you want the user to click the button then you will need to rewirte your code a bit and put some code in RowDeleting() as #Cal279 sugested in his comment.

Categories