Handling empty databound dropdown list in ASP.Net - asp.net

I have an asp.net page that has the following form fields:
Dropdown 1. This drop down receives the data via SQL data source.
Dropdown 2. Based on the selection of the drop down 1, this drop down queries to the database using SQL datasource and is populated.
A panel control that is placed below drop down list 2 and it has a set of the controls.
My problem is there may be a situation when nothing is returned from the datasource of drop down 2, I want to show an Item "No Data found" in the dropdown list 2 and simultaneously hide the panel that is placed below dropdown 2.
Can someone please let me know how this situation can be handled.
Appreciate the help.
Thanks,
Yagya

Add the following code to your dropdownlist1 selected index change event.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// Run this code when your sql datasource 2 does not return record, you can also place an IfElse condition
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Value");
DataRow row = dt.NewRow();
row[0] = "-1";
row[1] = "Data Not Found";
dt.Rows.Add(row);
DropDownList2.DataSource = dt;
DropDownList2.DataTextField = "Value";
DropDownList2.DataValueField = "ID";
DropDownList2.DataBind();
}
Updated answer: ( Try this one )
You can also place it in your sqldatasource2 selecting event.
protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
if (e.Arguments.TotalRowCount == 0)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Value");
DataRow row = dt.NewRow();
row[0] = "-1";
row[1] = "Data Not Found";
dt.Rows.Add(row);
DropDownList2.DataSource = dt;
DropDownList2.DataTextField = "Value";
DropDownList2.DataValueField = "ID";
DropDownList2.DataBind();
}
}
The above code will add a Item to your dropdownlist having Text = "Data Not Found"

Related

how to bind combobox and web service in asp.net

I have a combo box and a web service. I want to call web service and then when I open my combo I see the values the are in my web service.My code did not work.Can anybody help me?
protected void Page_Load(object sender, EventArgs e)
{
string firstParam = "1";
DataSet ds2 = ws1.Automation_H022_MamooriyatSaati_View(firstParam, secondParam, thirdParam);
this.GridView1.DataSource = ds2;
foreach (System.Data.DataTable table1 in ds1.Tables)
{
foreach (DataRow dr in table1.Rows)
{
cmbox.DataTextField = "Tp_Place";
cmbox.DataValueField = "Lg_Personality";
cmbox.DataBind();
cmbox.Items.Insert(0, new ListItem("", "1"));
}
}
}
You are adding not adding anything to the cmbox in the foreach (DataRow dr in table1.Rows). And even if you did the next loop would overwrite it.
You need to set the datasource for the ComboBox in the same way you set the GridView.
If there is more than one table in ds1 and you want both tables to be visible in the combobox then you need to merge those two (or more) tables first and then bind them as a single source of data.
DataSet ds2 = ws1.Automation_H022_MamooriyatSaati_View(firstParam, secondParam, thirdParam);
this.GridView1.DataSource = ds2;
cmbox.DataSource = ds1.Tables[0];
cmbox.DataTextField = "Tp_Place";
cmbox.DataValueField = "Lg_Personality";
cmbox.DataBind();
cmbox.Items.Insert(0, new ListItem("", "1"));

Add New Rows to GridView

I have a GridView on my page and on a button_OnClick event I'm wanting to add a new row to the grid.
I can add a row to the table using the following code, which works fine, but as I'm binding the DataTable to the grid any previous entries are lost.
string selectedProduct= ddlProducts.SelectedItem.Text;
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Product");
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataTable.Rows.Add(dataRow);
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
So whilst I understand why this is causing the data loss, I'm not really sure how to get around it.
How can I add a new row to the GridView on each button click whilst retaining the previously added row? The data is not stored anywhere other than the grid itself, so there is no real datasource.
There are options such as Add row to gridview on client side which uses Jquery, but I have read that it isn't a great idea to use that when adding / removing items from the grid. Perhaps that is wrong? Or there is this Add new row to gridview but there isn't much detail there.
You need to store the Products into ViewState (or SessionState or Database) so that it can persist on post back.
For example,
private DataTable ProductDataTable
{
get { return ViewState["ProductDataTable"] as DataTable ?? new DataTable(); }
set { ViewState["ProductDataTable"] = value; }
}
protected void AddRowButton_Click(object sender, EventArgs e)
{
string selectedProduct = ddlProducts.SelectedItem.Text;
// Get the data from ViewState
DataTable dataTable = ProductDataTable;
dataTable.Columns.Add("Product");
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataTable.Rows.Add(dataRow);
// Save the data back to ViewState
ProductDataTable = dataTable;
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
}
Here is a sample you can try:
DataTable dt = new DataTable(); 
if (ViewState["CurrentTable"]!=null)
{
dt = (DataTable)ViewState["CurrentTable"];
  }
else
{
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
}
DataRow dr = null;            
dr = dt.NewRow();
dr["Col1"] = "tes";      
dr["Col2"] = "test";
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt; 
GridView1.DataSource = dt; 
GridView1.DataBind();
Sorry for bad formatting, typed this with my cellphone. Hope it helps! :-)
// OnButten click
function addrow(sender, args) {
// td add as per your column required
$("#GridView1 tbody").append('<tr><td>00001</td><td>Mr.</td><td>LOKESH N</td></tr>');
}

how to get gridview all rows data when using paging

I have a gridview with paging (page size 10), which contains Course details. when i am saving gridview data into database it save only 10 record (according to page).
is there any to get all gridview all rows.
e.g. if my gridview contains 25 rows with paging and when i save data into database then all 25 rows data insert into database?
please help...
Here is my code
DataTable dt = new DataTable();
dt.Columns.Add("row_index");
dt.Columns.Add("edited_value");
IList<int?> SeqNos = new List<int?>();
foreach (GridViewRow gvr in gvViolationCodes.Rows)
{
TextBox tb = (TextBox)gvr.FindControl("txtSeqNo");
Label lblSysid = (Label)gvr.FindControl("lblSysID");
HiddenField hf = (HiddenField)gvr.FindControl("HiddenField1");
if (tb.Text != hf.Value)
{
DataRow dr = dt.NewRow();
SeqNos.Add(Convert.ToInt32(tb.Text));
dr["row_index"] = lblSysid.Text;
dr["edited_value"] = tb.Text;
dt.Rows.Add(dr);
}
}
You need to save the data in temporary storage in PageIndexChanging event of GrIdView. On final save send the datatable to Sql Server Procedure or loop through the datatable and save it in database. Follow the steps:
protected void grdView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
fnStoreGridData();
}
private void fnStoreGridData()
{
DataTable TempDataTable = new DataTable();
if(Session["Data"]!=null){
TempDataTable = Session["Data"] as DataTable;
}
else{
TempDataTable.Columns.Add("exCourse", typeof(string)) ;
TempDataTable.Columns.Add("exUniversityCourse", typeof(string)) ;
}
foreach (GridViewRow row in gvExportCourse.Rows)
{
Label exCourse = (Label)row.FindControl("gvlblCourseName");
Label exUniversityCourse = (Label)row.FindControl("gvlblUniversityCourseName");
if (exCourse != null)
{
if (!string.IsNullOrEmpty(exCourse.Text))
{
TempDataTable.Rows.Add(exCourse.Text, exUniversityCourse.Text);
//TempDataTable is your datatable object. Make sure that datatable contains these columns
}
}
}
}
In Final Save:
protected void button_Click(object s, EventArg e)
{
fnStoreGridData(); //Here this will bind the data of current page
DataTable TempDataTable = new DataTable();
if(Session["Data"]!=null){
TempDataTable = Session["Data"] as DataTable;
}
//Now loop through datatable and store the values
foreach(DataRow in TempDataTable.Rows)
{
CourseInformation course = new CourseInformation();
course.AddCourseMaster(dr["exCourse"].ToString(), dr["exUniversityCourse"].ToString());
}
label1.Text = "Course saved successfully.";
}

How to store ButtonField in a datarow where the column is set for ButtonField

consider the following code
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dtCol = new DataColumn();
dtCol = new DataColumn("Name", typeof(string));
dt.Columns.Add(dtCol);
dtCol = new DataColumn("Address", typeof(string));
dt.Columns.Add(dtCol);
dtCol = new DataColumn("Account No", typeof(ButtonField));
dt.Columns.Add(dtCol);
ButtonField bfname = new ButtonField {
HeaderText = "Account No",
DataTextField="Account No",
Text = "Klik",
ButtonType = ButtonType.Link,
CommandName = "ExecuteMe" };
string[] strDataRow = new string[3];
for (int intX = 0; intX < 10; intX++)
{
strDataRow[0] = "Name" + Convert.ToString(intX);
strDataRow[1] = "Address" + Convert.ToString(intX);
strDataRow[2] = bfname.Text; //Error Type of value has a mismatch with column typeCouldn't store <Account No0> in Account No Column. Expected type is ButtonField.
ButtonField btnField = bfname; // No Error but not appear in GridView1
dt.Rows.Add(new object[] {strDataRow[0], strDataRow[1], strDataRow[2]});
//dt.Rows.Add(new object[] { strDataRow[0], strDataRow[1], btnField }); // No Error but not appear in GridView1
/* Error Message on strDataRow[2]
Type of value has a mismatch with column typeCouldn't store <Account No0> in Account No Column. Expected type is ButtonField.
*/
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
How do I store ButtonField in a datarow where the column is set for ButtonField. How the ButtonField.Text appear in each DataRow
And
Is it possible to store string value in a datarow which is the column is set for ButtonField. When the string is click , then the ButtonField.CommandName will execute.
Note* : The GirdView code in ASPX page as follows.
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
Im not sure about your question, but instead of put the button in the DataTable, what I suposed as impossible why not create a GridView and add a TemplateField containing your button.

Dropdownlist on gridview updating only first value to the database ASP.Net

I am looking for the solution to this problem from many days, please help.
I have a grid view and have five dropdownlist on it. I have edit update and cancel edit buttons on each row.
Drop down list is updating the database, but only first value in the dropdownlist even when user select second, third or any other value from the dropdownlist.
What could possible be the reason for this. Here is my row Edit/ CancelEdit and Updating Events.
protected void gvCustomers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void gvCustomers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}
protected void gvCustomers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblCustId = (Label)gvCustomers.Rows[e.RowIndex].FindControl("cust_id");
DropDownList ddlCsm = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("CSM");
DropDownList ddlSrCsm = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("SrCSM");
DropDownList ddlDE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("DE");
DropDownList ddlAE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("AE");
DropDownList ddlTE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("TE");
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
string sql = "Update SOME_TABLE SET CSM= #CSM, SrCSM= #SrCSM ,DE=#DE,AE=#AE,TE=#TE where cust_id=#cust_id";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#CSM", SqlDbType.VarChar).Value = ddlCsm.SelectedItem.Value;
cmd.Parameters.Add("#SrCSM", SqlDbType.VarChar).Value = ddlSrCsm.SelectedItem.Value;
cmd.Parameters.Add("#AE", SqlDbType.VarChar).Value = ddlAE.SelectedItem.Value;
cmd.Parameters.Add("#DE", SqlDbType.VarChar).Value = ddlDE.SelectedItem.Value;
cmd.Parameters.Add("#TE", SqlDbType.VarChar).Value = ddlTE.SelectedItem.Value;
cmd.ExecuteNonQuery();
}
}
catch
{ }
gvCustomers.EditIndex = -1;
BindData();
}
}
Any help would be greatly appeciated.
Thanks
just fill the dropdowns on the click of edit button and then use on rowupdating event and use ddl.SelectedValue instead of ddl.SelectedItem.Value. You will find the selected values.
Your Drop Downs are probably getting re-set in your Page_Load event. If they are, load them when the page is not in postback, like so:
if(!Page.IsPostBack) {
//set drop downs
}

Resources