2014年7月13日 星期日

[RESOLVED] How do I validate SelectionButton?


On my gridview markup, I have this:



When creating a record, you must click on a particular row to make that row selectable.


If you don't do this, "Cannot insert null into column {someID}.


I have added CausesValidation="True" as you can see above so it forces users to click on a row to select it before proceeding.


However, I am still getting same null value error.


Is there a way to handle this so that if a user tries to insert a record without first clicking on a particular row, an exception is raised warning the user that a selection must be made before proceeding?


Thanks always for all the help


 



On the Gridview you need to use the property RowEditing.


You can code logic in here to validate the columns on the row when the user clicks on it.


 



Try set initial selectedindex to zero




I dont know what your insert code looks like, showing the code will be better



Hello sir.


Good to hear from you.


Here is the insert using sqldatasource:


InsertCommand="INSERT INTO [SurveyChoices] ([QuestionID], [Choice],[IsCorrect]) VALUES (@QuestionID, @Choice,CASE WHEN @IsCorrect ='False' THEN 0 ELSE 1 end)"

I really don't want to trick it by adding zero as default value.


What would be nice is to add some validation so that in the event that a user fails to click to select a row, they get a message informing that they need to select a row first before continuing.


Is this possible?



Maybe like this


       if (GridView1.SelectedIndex > -1)
{
//do insert
}

or


        if (GridView1.SelectedIndex > -1)
{
//do insert
}
else
{
MessageLabel.Text = "please select";
}









Does it mean that I move the insert code to codebehind?



yes, server side validation



Thanks for your help sir.


Only issue I will have though is that I am also doing update and delete commands using same sqldatasource.


DeleteCommand="DELETE FROM [SurveyChoices] WHERE [ChoiceID] = @ChoiceID"
InsertCommand="INSERT INTO [SurveyChoices] ([QuestionID], [Choice],[IsCorrect]) VALUES (@QuestionID, @Choice,CASE WHEN @IsCorrect ='False' THEN 0 ELSE 1 end)"
SelectCommand="SELECT * FROM [SurveyChoices] WHERE ([QuestionID] = @QuestionID)"
UpdateCommand="UPDATE [SurveyChoices] SET [QuestionID] = @QuestionID, [Choice] = @Choice WHERE [ChoiceID] = @ChoiceID">

So, how do I move all of these to server side?



try this


protected void SqlDataSource1_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
if(GridView1.SelectedIndex < 0)
{
e.Cancel = true;
}
}







It worked sir.


Thank you for all the help you provide me.


沒有留言:

張貼留言