To retain the searched data you need to pass the textbox value as parameter to command object.
Refer below links for more details.
I have modified your code. Refer below code and modify as per your requirement.
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
function ShowPopup() {
$("#btnShowPopup").click();
}
function GetData(CustomerId) {
document.getElementById('<%=UpdateId.ClientID%>').value = CustomerId;
document.getElementById('<%=hidUpdate.ClientID%>').value = "GetData";
document.forms[0].submit();
}
function Reset() {
document.getElementById('<%=UpdateId.ClientID%>').value = "";
document.getElementById('<%=hidUpdate.ClientID%>').value = "";
}
function Update() {
var fv = document.getElementById('<%=txt_rolename.ClientID%>').value;
//Change these conditions as your requirement
if (fv.length != "") {
swal({
title: "Are you sure?",
text: "You want to Update!",
type: "warning", showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, Update it!",
cancelButtonText: "No, Cancel Please!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal({
title: 'Updated!',
text: 'Your record has been Updated.',
type: 'success'
}, function () {
document.getElementById('<%=hidUpdate.ClientID%>').value = "Update";
document.forms[0].submit();
});
} else {
swal("Cancelled", "Your record is safe :)", "error");
}
});
}
else {
swal("Validate", "Please Enter Role Name", "error");
}
}
function Delete(CustomerId) {
swal({
title: "Are you sure?",
text: "You want to Delete!",
type: "warning", showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, Delete it!",
cancelButtonText: "No, Cancel Please!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal({
title: 'Deleted!',
text: 'Your record has been Deleted.',
type: 'success'
}, function () {
document.getElementById('<%=DeleteId.ClientID%>').value = CustomerId;
document.getElementById('<%=hidDelete.ClientID%>').value = "Delete";
document.getElementById('<%=hidUpdate.ClientID%>').value = "";
document.forms[0].submit();
});
} else {
swal("Cancelled", "Your record is safe :)", "error");
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" ScriptMode="Release">
</asp:ToolkitScriptManager>
<button type="button" class="btn btn-primary btn-lg" style="display: none;" id="btnShowPopup"
data-toggle="modal" data-target="#myModal">
Open Modal</button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×</button>
</div>
<div class="modal-body">
<div class="card-body ">
<div class="row">
<label>
Country Name</label>
<div class="col-sm-10">
<div class="form-group">
<asp:TextBox ID="txt_rolename" class="form-control" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator runat="server" ControlToValidate="txt_rolename" ForeColor="Red"
SetFocusOnError="true" Display="Dynamic" ErrorMessage="No special characters/digits"
ID="RegularExpressionValidator1" ValidationExpression="^[\sa-zA-Z]*$"> </asp:RegularExpressionValidator>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<asp:LinkButton ID="btn_complain_cancel" runat="server" class="btn btn-danger btn-wd "
data-dismiss="modal" OnClientClick="Reset()"> Cancel</asp:LinkButton>
<p id="btn_complain_update" runat="server" text="Update" class="btn btn-primary btn-wd"
onclick="Update()">
Update</p>
</div>
</div>
</div>
</div>
</div>
<br />
<div class="form-group col-lg-12">
<label runat="server" id="Label3">
Search By Country</label>
<asp:TextBox ID="txt_search" runat="server" placeholder="Type here.." class="form_control"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please Enter Country Name"
ControlToValidate="txt_search" ForeColor="Red" ValidationGroup="G1"></asp:RequiredFieldValidator>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" CompletionSetCount="1"
MinimumPrefixLength="1" ServiceMethod="GetValues" TargetControlID="txt_search">
</asp:AutoCompleteExtender>
<%-- <ajax:autocompleteextender id="AutoCompleteExtender1" runat="server" targetcontrolid="txt_search"
minimumprefixlength="1" enablecaching="true" completionsetcount="1" completioninterval="1000"
servicemethod="GetValues">
</ajax:autocompleteextender>--%>
<asp:LinkButton ID="LinkButton3" runat="server" class="btn btn-warning btn-wd" OnClick="btn_search_Click"
ValidationGroup="G1">Search by Name</asp:LinkButton>
</div>
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="CustomerId" HeaderText="Customer ID" />
<asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
<asp:BoundField ItemStyle-Width="150px" DataField="Country" HeaderText="Country" />
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" class="btn btn-link btn-warning edit" Text="Edit"
runat="server" OnClientClick=<%# " GetData('" + Eval("CustomerId") +"')" %>><i class="fa fa-edit"></i>
<a href="javascript:Delete('<%# DataBinder.Eval(Container.DataItem,"CustomerId")%>');" class="btn btn-link btn-danger remove"><i class="fa fa-times"></i>
</asp:LinkButton>
<%-- <asp:LinkButton ID="LinkButton1" runat="server" OnClientClick=<%# " GetData('" + Eval("CustomerId") +"')" %>>Edit
<a href="javascript:Delete('<%# DataBinder.Eval(Container.DataItem,"CustomerId")%>');" >Delete
</asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<input id="hidUpdate" runat="server" type="hidden" />
<input id="UpdateId" runat="server" type="hidden" />
<input id="hidDelete" runat="server" type="hidden" />
<input id="DeleteId" runat="server" type="hidden" />
</form>
</body>
</html>
Code
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (Request.Form[hidUpdate.UniqueID].ToString() == "GetData")
{
btn_complain_update.Visible = true;
GetData();
}
if (Request.Form[hidUpdate.UniqueID].ToString() == "Update")
{
UpdateData();
hidUpdate.Value = "";
this.BindGrid(txt_search.Text);
}
if (Request.Form[hidDelete.UniqueID].ToString() == "Delete")
{
DeleteData();
hidUpdate.Value = "";
this.BindGrid(txt_search.Text);
}
}
this.BindGrid(txt_search.Text);
}
private void BindGrid(string country)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
using (SqlCommand cmd = new SqlCommand())
{
string query = "";
if (string.IsNullOrEmpty(country))
{
query = "SELECT CustomerID,ContactName,City,Country FROM Customers";
cmd.CommandText = query;
}
else
{
query = "SELECT CustomerID,ContactName,City,Country FROM Customers WHERE Country=@Country";
cmd.Parameters.AddWithValue("@Country", country);
}
cmd.CommandText = query;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
this.GridView1.PageIndex = 0;
ViewState["Data"] = dt;
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.GridView1.PageIndex = e.NewPageIndex;
this.BindGrid(txt_search.Text);
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetValues(string prefixText)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT CustomerID,ContactName,City,Country FROM Customers WHERE Country like @Country+'%' ", con);
cmd.Parameters.AddWithValue("@Country", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> sur_name = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
sur_name.Add(dt.Rows[i][3].ToString());
}
return sur_name;
}
protected void btn_search_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
DataTable dt = new DataTable();
string select = "SELECT CustomerID,ContactName,City,Country FROM Customers WHERE Country='" + txt_search.Text + "'";
SqlDataAdapter sda = new SqlDataAdapter(select, con);
sda.Fill(dt);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
private void ShowModal()
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowPopup();", true);
}
private void GetData()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowPopup();", true);
string idd = UpdateId.Value;
DataTable dt = new DataTable();
string select = "SELECT CustomerId, ContactName, City, Country FROM Customers where CustomerId='" + idd + "'";
SqlDataAdapter sda = new SqlDataAdapter(select, con);
sda.Fill(dt);
txt_rolename.Text = dt.Rows[0][3].ToString();
}
private void UpdateData()
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["crm_db"].ConnectionString);
int idd = Convert.ToInt32(UpdateId.Value);
string query1 = "update Customers set Country='" + txt_rolename.Text + "' where CustomerId='" + idd + "'";
SqlCommand update = new SqlCommand(query1, con1);
con1.Open();
update.ExecuteNonQuery();
con1.Close();
}
private void DeleteData()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["crm_db"].ConnectionString);
int id = Convert.ToInt32(DeleteId.Value);
string query1 = "delete Customers where CustomerId='" + id + "'";
SqlCommand update = new SqlCommand(query1, con);
con.Open();
update.ExecuteNonQuery();
con.Close();
}